Home >Backend Development >C#.Net Tutorial >What is the difference between Monitor and Lock in C#?

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

王林
王林forward
2023-09-08 21:13:07764browse

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

Both monitors and locks provide mechanisms for synchronizing object access. lock is a shortcut for Monitor.Enter and try and finally.

Lock is a shortcut and an option for basic usage. If we need more control use TryEnter(), Wait(), Pulse() and & for advanced multi-threading solutions PulseAll() method, then the Montior class is your choice.

Lock Example -

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++;
      }
   }
}

Monitor Example

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);
         }
      }
   }
}

The above is the detailed content of What is the difference between Monitor and Lock in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete