Difference between Monitor and lock in C#:-
Both Monitor class and lock provides a mechanism that synchronizes access to objects. lock is the shortcut for Monitor.Enter with try and finally.
This means that, the following code :-
In C# 4, it is implement slightly differently as shown below
So, in short, lock is a shortcut and it's the option for the basic usage. If you need more control to implement advanced multithreading solutions using TryEnter() Wait(), Pulse(), & PulseAll() methods, then the Monitor class is your option.
This means that, the following code :-
static object _lock = new object(); public static void AddOneMillion() { for (int i = 1; i <= 1000000; i++) { lock (_lock) { Total++; } } } can be rewritten as shown below: static object _lock = new object(); public static void AddOneMillion() { for (int i = 1; i <= 1000000; i++) { // Acquires the exclusive lock Monitor.Enter(_lock); try { Total++; } finally { // Releases the exclusive lock Monitor.Exit(_lock); } } }
In C# 4, it is implement slightly differently as shown below
static object _lock = new object(); public static void AddOneMillion() { for (int i = 1; i <= 1000000; i++) { bool lockTaken = false; // Acquires the exclusive lock Monitor.Enter(_lock, ref lockTaken); try { Total++; } finally { // Releases the exclusive lock if (lockTaken) Monitor.Exit(_lock); } } }
So, in short, lock is a shortcut and it's the option for the basic usage. If you need more control to implement advanced multithreading solutions using TryEnter() Wait(), Pulse(), & PulseAll() methods, then the Monitor class is your option.