Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

Monitor — locking and waiting for a condition

System.Threading.Monitor combines mutual exclusion with waiting for shared state to change. Enter and Exit manage the lock, TryEnter can bound acquisition waiting, and Wait, Pulse, and PulseAll coordinate threads.

Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification

Syntax

Monitor.Enter(gate, ref lockTaken);
Monitor.Exit(gate);
bool acquired = Monitor.TryEnter(gate, millisecondsTimeout);
bool signaled = Monitor.Wait(gate);
Monitor.Pulse(gate);
Monitor.PulseAll(gate);

System.Threading.Monitor protects shared state with a lock associated with a particular object. All cooperating threads must use the same instance, preferably a private readonly object. Avoid strings and values subject to boxing. These APIs are available in .NET 10; the example requires no preview language features.

Monitor.Enter waits to acquire the lock, and Monitor.Exit releases it. The lock is reentrant: the same thread can enter repeatedly but needs an equal number of Exit calls. Release it in finally; with Enter(gate, ref lockTaken), initialize lockTaken = false and call Exit only after acquisition. Monitor.TryEnter attempts acquisition without waiting or with a timeout; its bool-returning overload reports success.

Monitor.Wait requires ownership: it releases the lock and blocks the thread, then reacquires the lock before returning normally. Monitor.Pulse notifies one waiting thread, whereas Monitor.PulseAll notifies all of them. Notification neither releases the lock nor transfers it immediately. Signals are not remembered when nobody is waiting. Test the condition in while, not if: the state may have changed by the time the lock is reacquired. A Wait timeout does not bound the time needed to reacquire the lock.

Calling Wait, Pulse, PulseAll, or Exit without owning the corresponding lock throws SynchronizationLockException. Monitor ownership is thread-affine; do not carry it across await. For an ordinary object, the lock statement uses a monitor. Since C# 13, lock on an expression typed as System.Threading.Lock uses a different mechanism: do not combine it with Monitor.Wait or monitor notifications.

Examples

using System;
using System.Threading;

internal static class Program
{
    private static readonly object gate = new();
    private static bool ready;
    private static int value;

    private static void Main()
    {
        var consumer = new Thread(() =>
        {
            bool lockTaken = false;
            try
            {
                Monitor.Enter(gate, ref lockTaken);
                while (!ready)
                    Monitor.Wait(gate);
                Console.WriteLine(value);
            }
            finally
            {
                if (lockTaken)
                    Monitor.Exit(gate);
            }
        });

        consumer.Start();
        lock (gate)
        {
            value = 42;
            ready = true;
            Monitor.PulseAll(gate);
        }
        consumer.Join();
    }
}

Result

42

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources