C# Monitor class in multithreading with examples

What Is Monitor Class In C#?

Monitor class: In C#, the Monitor class provides a wait based synchronization mechanism that allows only one thread to access a critical section of code at a time to avoid the race condition.
Here all the other threads have to wait and halt the execution until the locked object is released.

The  Monitor.Enter  method is used to acquire an exclusive lock on the object whereas  Monitor.Exit  method is used to release the locked object.

In order to use the Monitor class in a multithreading , we first need to import the  System.Threading  namespace.

C# Monitor class in multithreading

C# Monitor Syntax

Following is the syntax to use the Monitor class

static object _lock = new object();
// Lock object
Monitor.Enter(_lock);
try
{
  // Critical piece of code
}

finally
{
 // Releasing object
   Monitor.Exit(_lock);
}

Example Of Monitor Class in Multithreading

Following is the example of Monitor class in C#

using System;
using System.Threading;
namespace MontitorExample
{
 class Program
  {
 static object _lock = new object();

 public static void PrintNumber()
  {   
  // Lock object

  Monitor.Enter(_lock);
  try
   {
    // Critical piece of code
              
    int threadId = Thread.CurrentThread.ManagedThreadId;
    Console.WriteLine($" Thread: {threadId} Entered into the critical section ");

    for (int num = 1; num <= 3; num ++)
     {

      Console.WriteLine($" num: {num}");
    //Pausing the thread execution for 2 seconds

      Thread.Sleep(TimeSpan.FromSeconds(2));

      }
   }

  catch (SynchronizationLockException exception)
      {
       Console.WriteLine(exception.Message);
      }

  finally
    { 
     // Releasing object
      Monitor.Exit(_lock);
      Console.WriteLine($"Thread : {Thread.CurrentThread.ManagedThreadId} Released");
    }           
  }
  static void Main(string[] args)
   {        
   // Creating threads
   Thread thread1 = new Thread(PrintNumber);
   Thread thread2 = new Thread(PrintNumber);

  // Executing the threads
   thread1.Start();
   thread2.Start();

  Console.ReadLine();      
   }
 }

}

Let’s run the above program to see the result.

C# Monitor class output
The output of the above program

Methods of the Monitor class

The Monitor class is a static class which contains the following methods:

      • Monitor.Enter
      • Monitor.TryEnter
      • Monitor.Exit
      • Monitor.Pulse
      • Monitor.PulseAll
      • Monitor.Wait

Monitor.Enter, Monitor.TryEnter : These methods are used to acquire an exclusive lock on the object, which allows only one thread to access the critical section of code at a time.

Monitor.Pulse, Monitor.PulseAll : A thread sends the signal to one or multiple threads in the waiting queue that the state of the locked object has been changed. So, that they can proceed for the further process.

Monitor.Wait(): This method is used to release the locked object after getting the Pulse notification to allow other threads to lock and access the object.

The calling threads waits in the waiting queue while the other thread is allowed to access the object until it gets the pulse notification.

Note: Wait() method must execute before the Pulse or PulseAll method to get the pulse notification.

Monitor.Exit: This method is used to release the locked object, and it is always declared inside finally block.

Difference between Lock and Monitor in C#

In C#, Both the  Lock  and  Monitor   class are basically used to ensure that only one thread can access a particular section of code at a time. 

The following are the basic differences between both classes:

    • A lock statement is a short form of the Monitor class which internally wraps the methods  Monitor.Enter  and  Monitor.Exit  with an additional  try/finally  block, to perform the thread-safe operation, whereas in the case of Monitor class, we have to declare try and finally block explicitly to  release the locked object.
    • Apart from the synchronization mechanism, the Monitor class provides some useful methods like Wait(), Pulse() and PulseAll() for the signaling mechanism between the threads. However, the lock doesn’t support the signaling mechanism.
    • Monitor is a static class which can’t be instantiated.

Conclusion

The Lock and Monitor class are generally used for the synchronization purpose in a multithreading environment.
They allow only one thread to access a critical section of code at a time.
The only major difference between both of them is that the Monitor class provides more control over synchronization by using the signaling mechanism.

Hope you enjoyed this post. Thanks for visiting.

Leave a Reply

Your email address will not be published. Required fields are marked *

4 + thirteen =