C# Reference ยท Keywords and Statements
The lock statement
Reference for the C# lock statement: protecting shared state, the dedicated Lock type in .NET 9, what to lock on, deadlocks and why await is not allowed inside.
lock allows only one thread at a time to run a block of code that guards shared data. A thread that reaches the lock waits until the lock is free, enters, and releases it when the block ends, even if an exception escapes. The lock is re-entrant: the thread that holds it may enter again.
Since .NET 9 the best lock object is an instance of System.Threading.Lock. When the compiler sees a Lock in a lock statement it calls EnterScope() instead of using the older Monitor calls, which is faster and clearly signals intent. Any reference type still works as before.
private readonly Lock _gate = new(); private int _count; public void Increment() { lock (_gate) { _count++; } }
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 (object) statement
| Name | Description |
|---|---|
object |
The lock object: an instance of System.Threading.Lock, or a reference type used with Monitor. It must not be null or a value type. |
Errors: locking a value type fails with CS0185; a null lock object throws ArgumentNullException at run time. Using await inside a lock block fails with CS1996.
Usage notes
- What to lock on: a private, readonly field that exists only for locking. Never lock on
this, aTypeobject, a string or any object other than your own private one, because outside code could lock it too and cause deadlocks. - Keep it short. Hold the lock for as little time as possible; do not call unknown callbacks, perform I/O or wait on tasks inside it.
- Async code. The block cannot contain
await, because a lock is owned by a thread, not by a task. UseSemaphoreSlim.WaitAsync()for async mutual exclusion. - Deadlocks happen when two threads take two locks in opposite orders. Always acquire locks in one global order, or use a single lock.
- Alternatives:
Interlockedfor single counters, concurrent collections,ReaderWriterLockSlimfor many readers,Channel<T>for message passing. - Memory effects: entering and leaving a lock act as full memory barriers, so data written inside the lock is visible to the next holder.
- Equivalent code: a classic object lock expands to
Monitor.EnterandMonitor.Exitin atry/finally. ALockobject expands tousing (gate.EnterScope()) { ... }.