0
0
CsharpConceptBeginner · 4 min read

What is Monitor in C#: Simple Explanation and Usage

Monitor in C# is a synchronization tool that controls access to a block of code by multiple threads to prevent conflicts. It works like a lock, allowing only one thread at a time to execute the protected code section, ensuring thread safety.
⚙️

How It Works

Imagine you have a single bathroom in a house shared by many people. To avoid chaos, only one person can use it at a time. Monitor works similarly in programming by allowing only one thread to enter a critical section of code at a time.

When a thread wants to run code protected by Monitor, it must first acquire a lock. If another thread already holds the lock, the new thread waits patiently until the lock is free. Once the thread finishes, it releases the lock so others can enter.

This mechanism prevents multiple threads from changing shared data simultaneously, which could cause errors or unpredictable results.

💻

Example

This example shows two threads trying to update a shared counter safely using Monitor. Only one thread can update the counter at a time.

csharp
using System;
using System.Threading;

class Program
{
    private static int counter = 0;
    private static readonly object lockObj = new object();

    static void Main()
    {
        Thread t1 = new Thread(IncrementCounter);
        Thread t2 = new Thread(IncrementCounter);

        t1.Start();
        t2.Start();

        t1.Join();
        t2.Join();

        Console.WriteLine($"Final counter value: {counter}");
    }

    static void IncrementCounter()
    {
        for (int i = 0; i < 1000; i++)
        {
            Monitor.Enter(lockObj);
            try
            {
                counter++;
            }
            finally
            {
                Monitor.Exit(lockObj);
            }
        }
    }
}
Output
Final counter value: 2000
🎯

When to Use

Use Monitor when you need to protect shared resources from being accessed by multiple threads at the same time. This is common in programs that do many things at once (multithreading) and share data like counters, lists, or files.

For example, if two threads try to update the same bank account balance simultaneously, Monitor ensures one finishes before the other starts, preventing mistakes.

It is especially useful when you want fine control over locking and unlocking code blocks manually.

Key Points

  • Monitor provides exclusive locking for thread safety.
  • It requires an object to lock on, usually a private object.
  • Use Monitor.Enter to lock and Monitor.Exit to unlock.
  • Always use try-finally to ensure the lock is released.
  • It helps avoid race conditions and data corruption in multithreaded programs.

Key Takeaways

Monitor controls access to code blocks by allowing only one thread at a time.
Always pair Monitor.Enter with Monitor.Exit inside a try-finally block to avoid deadlocks.
Use Monitor to protect shared data in multithreaded applications.
Monitor requires a private object to lock on for synchronization.
It helps prevent race conditions and ensures thread safety.