Home >Backend Development >C#.Net Tutorial >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 -
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−
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!