What is C# monitor class? Explain monitor pulse wait by example

(Last Updated On: May 6, 2017)

Answer includes C# monitor class with program example in threaded program and its pulse wait method. Monitor class in C# multi-threaded program is used to synchronize the shared resources i.e. file IO, shared data and memory etc. among threads. Monitor class is available in namespace System.Threading.

Besides synchronization mechanism, Monitor class also provides wait (), pulse () and pulseAll() methods for signalling / communication between threads.

Below program demonstrate the use of C# monitor class object to synchronize the shared resource that is command console in printer method between two threads as both threads are printing the output on common console.

 

Monitor pulse, wait and pulseAll Method

Brief description of these pulse, wait and pulseAll methods.

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.

Read the thread program example to how to use pulse and wait method for signaling in odd and even numbers printing using two threads.

NOTE
We must use try and finally block to hold lock and release lock respectively using monitor class for synchronization, as if we don’t release lock in finally code, on exception, lock will not be released and application will hang.

Lock can also be used to synchronize shared resources. However, there is difference between monitor and lock synchronization .

If you want to see the affect, you can comment Monitor.Exit(monitor) in finally block and see that application will hang.