Monitor

This lesson explains how the Monitor class in C# works and its related caveats.

Monitor

The Monitor class exposes static methods to synchronize access to objects. The following static methods are commonly used to work with the Monitor class:

  • Enter()

  • Exit()

  • Wait()

  • Pulse()

  • PulseAll()

Synchronization on an object means that an exclusive lock is acquired on an object by a thread that invokes Enter(). All other threads invoking Enter() get blocked till the first thread exits the monitor by invoking Exit(). As a consequence, the code block sandwiched between the enter and exit calls becomes a critical section with only one thread active in the block at any given time.

As an example consider the snippet below:

Press + to interact
public void example()
{
Monitor.Enter(this);
// Critical section
Console.WriteLine("Thread with id " + Thread.CurrentThread.ManagedThreadId + " enters the critical section.");
Thread.Sleep(3000);
Console.WriteLine("Thread with id " + Thread.CurrentThread.ManagedThreadId + " exits the critical section.");
Monitor.Exit(this);
}

The monitor synchronizes on the this object in the example above. We could have used any reference object other than this with the same results. We run the above example in the code-widget below. Three threads are created and ran through the critical section. Within the critical section, each thread sleeps for three seconds to simulate useful work. However, because the monitor serializes thread access to the critical section, the total ...