What is the difference between Monitor and Lock in C#?

CsharpServer Side ProgrammingProgramming

Both Monitor and lock provides a mechanism that synchronizes access to objects. lock is the shortcut for Monitor.Enter with try and finally.

Lock is a shortcut and it's the option for the basic usage. If we need more control to implement advanced multithreading solutions using TryEnter() Wait(), Pulse(), & PulseAll() methods, then the Montior class is your option.

Example for Lock

Example

class Program{
static object _lock = new object();
static int Total;
public static void Main(){
   AddOneHundredLock();
   Console.ReadLine();
}
public static void AddOneHundredLock(){
   for (int i = 1; i <= 100; i++){
      lock (_lock){
         Total++;
      }
   }
}

Example for Monitor 

Example

class Program{
   static object _lock = new object();
   static int Total;
   public static void Main(){
      AddOneHundredMonitor();
      Console.ReadLine();
   }
   public static void AddOneHundredMonitor(){
      for (int i = 1; i <= 100; i++){
         Monitor.Enter(_lock);
         try{
            Total++;
         }
         finally{
            Monitor.Exit(_lock);
         }
      }
   }
}
raja
Published on 19-Aug-2020 17:05:55
Advertisements