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.
using System;
using System.Threading;
namespace monitor_demo
{
class Program
{
static object monitor = new object();
static void Main(string[] args)
{
//Both thread will print a same string on console.
Thread t1 = new Thread(printer);
Thread t2 = new Thread(printer);
t1.Start();
t2.Start();
}
static void printer()
{
String arr = "Printer is printing!!!";
try
{
//hold lock as console is shared between threads.
Monitor.Enter(monitor);
for (int i = 0; i < arr.Length; i++)
{
Console.Write(arr[i]);
}
}
finally
{
//Release lock
Monitor.Exit(monitor);
}
}
}
}
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.