top
April flash sale

Search

C# Tutorial

Synchronization in C# is a mechanism that makes sure only one process or thread accesses the critical section of the program. All the other threads have to wait until the critical section is free before they can enter it.Some of the advantages of thread synchronization is given as follows:Synchronization can be used to achieve mutual exclusion i.e. only one process or thread accesses the critical section of the program.No thread or process has an infinite waiting time using synchronization.Synchronization is an inherently fair process.All the requests are granted in a specific order using synchronization.Synchronization can be used for resource allocation as well. It makes sure that only one process or thread can use a resource at a time.Methods to manage SynchronizationSynchronization can be handled using various methods. These methods are divided into 4 categories in general. These are as follows:Blocking MethodsLocking ConstructsNo blocking synchronizationSignalingPrograms that demonstrate a few of the above methods are given as follows:JoinIn thread synchronization, join is a blocking mechanism that pauses the calling thread. This is done till the thread whose join method was called has completed its execution.A program that demonstrates the join method is given as follows:using System; using System.Threading; namespace JoinDemo {   class Example       {      static void Main(string[] args)        {        Thread t1 = new Thread(Func1);            t1.Start();            Thread t2 = new Thread(Func2);            t2.Start();            t1.Join();            t2.Join();        }    private static void Func2(object obj)        {        Console.WriteLine("Thread1 is executed");        }    private static void Func1(object obj)        {        Console.WriteLine("Thread2 is executed");        }  }The output of the above program is as follows:Thread2 is executed Thread1 is executedLockLock is a synchronization method that is used to lock in the current thread so that no other thread can interrupt the execution of the locked thread. After the thread execution is complete, it is unlocked.A program that demonstrates the lock method is given as follows:Source Code: Program to implement synchronization lock() method in C#using System;   using System.Threading;   namespace LockDemo {   class LockDisplay     {      public void DisplayNum()       {          lock (this)           {              for (int i = 1; i <= 5; i++)               {                  Thread.Sleep(100);                   Console.WriteLine("i = {0}", i);               }          }      }    }    class Example   {      public static void Main(string[] args)       {          LockDisplay obj = new LockDisplay();                    Console.WriteLine("Threading using Lock");                  Thread t1 = new Thread(new ThreadStart(obj.DisplayNum));           Thread t2 = new Thread(new ThreadStart(obj.DisplayNum));           t1.Start();           t2.Start();       }    }  }The output of the above program is as follows:Threading using Lock i = 1 i = 2 i = 3 i = 4 i = 5 i = 1 i = 2 i = 3 i = 4 i = 5
logo

C# Tutorial

Synchronization in C#

Synchronization in C# is a mechanism that makes sure only one process or thread accesses the critical section of the program. All the other threads have to wait until the critical section is free before they can enter it.

Some of the advantages of thread synchronization is given as follows:

  1. Synchronization can be used to achieve mutual exclusion i.e. only one process or thread accesses the critical section of the program.
  2. No thread or process has an infinite waiting time using synchronization.
  3. Synchronization is an inherently fair process.
  4. All the requests are granted in a specific order using synchronization.
  5. Synchronization can be used for resource allocation as well. It makes sure that only one process or thread can use a resource at a time.

Methods to manage Synchronization

Synchronization can be handled using various methods. These methods are divided into 4 categories in general. These are as follows:

  1. Blocking Methods
  2. Locking Constructs
  3. No blocking synchronization
  4. Signaling

Programs that demonstrate a few of the above methods are given as follows:

Join

In thread synchronization, join is a blocking mechanism that pauses the calling thread. This is done till the thread whose join method was called has completed its execution.

A program that demonstrates the join method is given as follows:

using System;
using System.Threading;
namespace JoinDemo
{
  class Example    
  {  
   static void Main(string[] args)    
   {
       Thread t1 = new Thread(Func1);    
       t1.Start();    
       Thread t2 = new Thread(Func2);    
       t2.Start();    
       t1.Join();    
       t2.Join();    
   }
   private static void Func2(object obj)    
   {
       Console.WriteLine("Thread1 is executed");    
   }
   private static void Func1(object obj)    
   {
       Console.WriteLine("Thread2 is executed");    
   }
 }

The output of the above program is as follows:

Thread2 is executed
Thread1 is executed

Lock

Lock is a synchronization method that is used to lock in the current thread so that no other thread can interrupt the execution of the locked thread. After the thread execution is complete, it is unlocked.

A program that demonstrates the lock method is given as follows:

Source Code: Program to implement synchronization lock() method in C#

using System;  
using System.Threading;  
namespace LockDemo
{
  class LockDisplay  
  { 
    public void DisplayNum()  
    { 
        lock (this)  
        { 
            for (int i = 1; i <= 5; i++)  
            { 
                Thread.Sleep(100);  
                Console.WriteLine("i = {0}", i);  
            } 
        } 
    } 
  } 
  class Example
  { 
    public static void Main(string[] args)  
    { 
        LockDisplay obj = new LockDisplay();  
        
        Console.WriteLine("Threading using Lock"); 
       
        Thread t1 = new Thread(new ThreadStart(obj.DisplayNum));  
        Thread t2 = new Thread(new ThreadStart(obj.DisplayNum));  
        t1.Start();  
        t2.Start();  
    } 
  } 
}

The output of the above program is as follows:

Threading using Lock
i = 1
i = 2
i = 3
i = 4
i = 5
i = 1
i = 2
i = 3
i = 4
i = 5

Leave a Reply

Your email address will not be published. Required fields are marked *

Comments

austin faith

Avery good write-up. Please let me know what are the types of C# libraries used for AI development.

kariya arti

very satisfied!!

jean-Francois Michaud

Good tutorial. Small question: Say, there is : enum numbers { one, two, three} and a string field_enum ="one" how would I from the variable field_enum have a response with value numbers.one so that it can be treated as an enum and not as a string. making a list from the enum, and loop into the list. is not elegant... and may not work is forced value on field is forced ( one = 100).

Kshitiz

Hi Team Knowledge Hut, Thank you for such an informative post like this. I am completely new to this digital marketing field and do not have much idea about this, but your post has become a supportive pillar for me. After reading the blog I would expect to read more about the topic. I wish to get connected with you always to have updates on these sorts of ideas. Regards, Kshitiz

Ed

The reason abstraction can be used with this example is because, the triangle, circle. Square etc can be defined as a shape, for example.....shape c = new circle(5,0)...the abstract object c now points at the circle class. Thus hiding implementation

Suggested Tutorials

Swift Tutorial

Introduction to Swift Tutorial
Swift Tutorial

Introduction to Swift Tutorial

Read More

R Programming Tutorial

R Programming

Python Tutorial

Python Tutorial