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.
private readonly Lock _gate = new(); lock (_gate) { counter++; }
Try it
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.
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
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, aType, or a string: outside code can lock on the same object and cause deadlocks. Useprivate 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
lockon a value type. awaitinsidelockis a compile error. The thread that releases the lock might not be the one that took it. UseSemaphoreSlimfor async mutual exclusion; see Mutex and SemaphoreSlim.- Always use
while, notif, aroundWait. 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.
lockexpands totry/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
Enterneeds a matchingExit. System.Threading.Lockis C# 13 / .NET 9. Older targets useobjectwith the same syntax.