C# Thread Synchronization | Thread Synchronization in C#



C# Thread Synchronization

  • Synchronization is a technique that allows only one thread to access the resource for the particular time and no other thread can interrupt until the assigned thread finishes its task.
  • Threads are allowed to access any resource for the required execution time, in multithreading programs.
  • Threads share resources and executes asynchronously and it is mainly used in case of transactions like deposit, withdraw etc.
  • Accessing shared resources (data) is critical task that sometimes may halt the system and we deal with by making threads synchronized.

Advantages of Thread Synchronization

  • No thread Interface
  • Consistency Maintain

C# Lock

  • We can use C# lock keyword to execute program synchronously and it ensures that other thread does not interrupt the execution until the execution finish.
  • It is used to get lock for the current thread and execute the task and then release the lock.

For example; without synchronization

using System;  
using System.Threading;  
class Printer  
{  
    public void PrintTable()  
    {  
        for (int i = 1; i <= 10; i++)  
        {  
            Thread.Sleep(100);  
            Console.WriteLine(i);  
        }  
    }  
}  
class Program  
{  
    public static void Main(string[] args)  
    {  
        Printer p = new Printer();  
        Thread t1 = new Thread(new ThreadStart(p.PrintTable));  
        Thread t2 = new Thread(new ThreadStart(p.PrintTable));  
        t1.Start();  
        t2.Start();  
    }  
}  

Output

1
1
2
2
3
3
4
4
5
5
6
6
7
7
8
8
9
9
10
10

For example; C# Thread synchronization

using System;  
using System.Threading;  
class Printer  
{  
    public void PrintTable()  
    {  
        lock (this)  
        {  
            for (int i = 1; i <= 10; i++)  
            {  
                Thread.Sleep(100);  
                Console.WriteLine(i);  
            }  
        }  
    }  
}  
class Program  
{  
    public static void Main(string[] args)  
    {  
        Printer p = new Printer();  
        Thread t1 = new Thread(new ThreadStart(p.PrintTable));  
        Thread t2 = new Thread(new ThreadStart(p.PrintTable));  
        t1.Start();  
        t2.Start();  
    }  
}  

Output

1
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10

Related Searches to C# Thread Synchronization | Thread Synchronization in C#