C# Lock Vs Monitor – Why Use Monitor instead of Lock

Answer: Lock Vs Monitor in C# multithreading: Difference between monitor and lock in C# is that lock internally wraps the Enter and Exit methods in a tryfinally block with exception handling. Whereas for Monitor class in C#, we use try and finally block explicitly to release lock properly.

Lock = Monitor + try finally.

Below is the source code of lock vs Monitor class used in below C# thread example.

Secondly, Monitor class has extra option that is signalling option, that is used to communicate/signal to other threads using wait(), pulse() and pulseAll() methods.

C# Monitor.wait(): A thread wait for other threads to notify.

Monitor.pulse(): A thread notify to another thread.

Monitor.pulseAll(): A thread notifies all other threads within a process.

Another important C# thread interview question is

if lock handles try and finally block internally and gives clean and readable code, then why to use Monitor class?

In fact, this is clear that lock gives clean code as mentioned in above example and we should not use monitor in above case. But, if in any program, we are using signalling options i.e. Monitor wait pulse C# methods and need to synchronize the critical section, we should go for Monitor class in C# multithreading.

Read the answer to the interview question how to print even and odd number sequence using two threads , where monitor class has been used for synchronization and signalling for multiple threads.

Related Posts