Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Async and Concurrency

The lock statement and Monitor

Reference for the C# lock statement, System.Threading.Lock and Monitor: protect shared state, use Wait and Pulse, avoid deadlocks and lock misuse.

The lock statement lets only one thread at a time run a block of code. Other threads that reach the same lock wait until the first one leaves. It is the simplest way to protect shared mutable state from race conditions.

Since .NET 9 the best lock object is an instance of System.Threading.Lock: the lock statement recognizes it and uses its faster EnterScope() API. For any other object, lock compiles to Monitor.Enter and Monitor.Exit in a try/finally. Monitor also offers Wait and Pulse for signaling between threads.

C#
private readonly Lock _gate = new();
lock (_gate)
{
    counter++;
}

Try it

C# Protecting a shared counter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Wait and Pulse, TryEnter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
lock (expression)
{
    // critical section
}

public static class Monitor
{
    public static void Enter(object obj);
    public static void Enter(object obj, ref bool lockTaken);
    public static bool TryEnter(object obj);
    public static bool TryEnter(object obj, int millisecondsTimeout);
    public static void Exit(object obj);
    public static bool Wait(object obj);
    public static bool Wait(object obj, int millisecondsTimeout);
    public static void Pulse(object obj);
    public static void PulseAll(object obj);
    public static bool IsEntered(object obj);
}

public sealed class Lock
{
    public void Enter();
    public bool TryEnter();
    public void Exit();
    public Lock.Scope EnterScope();
    public bool IsHeldByCurrentThread { get; }
}
Name Description
obj The object whose lock is taken. It must be a reference type.
millisecondsTimeout How long to wait; Timeout.Infinite waits forever.
lockTaken Set to true only if the lock was acquired; used by compiler-generated code.

Returns: TryEnter returns true if the lock was acquired. Wait returns false if the timeout elapsed before a pulse.

Errors: Exit, Wait and Pulse throw SynchronizationLockException if the current thread does not hold the lock.

Usage notes

  • Lock on a private, dedicated object. Never lock on this, a Type, or a string: outside code can lock on the same object and cause deadlocks. Use private readonly Lock _gate = new();.
  • Do not lock on a value type. Boxing creates a new object every time, so nothing is protected. The compiler rejects lock on a value type.
  • await inside lock is a compile error. The thread that releases the lock might not be the one that took it. Use SemaphoreSlim for async mutual exclusion; see Mutex and SemaphoreSlim.
  • Always use while, not if, around Wait. A waiting thread can wake up when the condition is not true any more.
  • Keep the critical section short and never call unknown code (callbacks, events, virtual methods) while holding a lock.
  • Deadlocks happen when two threads take two locks in opposite order. Pick one global order. See Deadlocks.
  • Exceptions release the lock. lock expands to try/finally, so the lock is freed even if the body throws; the protected data may still be half-updated.
  • Reentrant. The same thread can lock the same object repeatedly; each Enter needs a matching Exit.
  • System.Threading.Lock is C# 13 / .NET 9. Older targets use object with the same syntax.