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#?

王林
Release: 2023-09-08 21:13:07
forward
763 people have browsed it

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++;
      }
   }
}
Copy after login

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);
         }
      }
   }
}
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template