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 with 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 wait 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.
    • The monitor is a static class that can’t be instantiated.

FAQ

What is the use of monitor class in C#?

The Monitor class in C# is used to provide thread safety in a multithreaded environment. Monitor class ensures that only one thread should allow accessing a critical section of code at a time to avoid the race condition between the threads. The methods Monitor.Enter and Monitor.Exit is used to lock and release the object or resource.

When should we use monitor wait method?

The Monitor.Wait() execute before the Pulse or PulseAll methods, It is used to block a process’s execution and to release the locked object after getting the Pulse notification to allow other threads to lock and access the object. The Monitor.Wait() method is an overloaded method that can have a timeout parameter to make sure that If the specified time-out interval elapses, the current thread enters the ready queue.

Are monitors better than semaphores?

The Monitors and Semaphores both are used for thread synchronization in multithreading applications. Here, the monitor class is simple and easy to use in comparison to semaphore as the monitor automatically acquires the necessary locks whereas in the case of a semaphore the resource has to explicitly acquire a lock before using the resource.

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.

I Hope you enjoyed this post. In case you have any doubt please post your questions in the comment section.

Thanks for visiting 🙂

Leave a Reply