In C#, what does the lock statement compile to, and which object should a class lock on to guard its shared state?
answer
- a class from System.Threading
- try/finally around the body
- same thread may enter again
- private readonly object field
basics
~20 sA C# lock (x) on an object becomes Monitor.Enter inside a try and Monitor.Exit in its finally, so an exception cannot leave the lock held. Lock on a private, dedicated object, never on this, a Type or a string.
solid answer
~50 sFor an object target, `lock (x) { ... }` compiles to `Monitor.Enter(x, ref lockTaken)` inside a `try`, with `Monitor.Exit(x)` in the `finally` when `lockTaken` is true, so an exception thrown in the body still releases the lock. One thread at a time runs the body; the thread that holds the lock may enter it again, and other threads block until it is released. The target must be a reference type: `lock` on an `int` is error CS0185. Use a `private readonly object _gate = new();` that nothing outside the class can reach. `lock (this)`, `lock (typeof(Foo))` and `lock ("orders")` all share the lock with code you do not control: callers hold `this`, anyone can get the `Type`, and string literals are interned. Keep the body short and put every read and write of the guarded state inside it.
code
csharp · 21 linesusing System.Threading;
var limiter = new RateLimiter(limit: 3);
for (int i = 1; i <= 5; i++)
Console.WriteLine($"request {i}: {(limiter.TryAcquire() ? "allowed" : "rejected")}");
class RateLimiter(int limit)
{
private readonly object _gate = new(); // private, dedicated, never exposed
private int _used;
public bool TryAcquire()
{
lock (_gate) // Monitor.Enter(_gate, ref taken) ... finally Monitor.Exit(_gate)
{
if (_used >= limit) return false; // check and update form one atomic step
_used++;
return true;
}
}
}go deeper
Recall the shape: lock on a private readonly object, keep the body short, and know that an exception in the body still releases the lock.
Explain the Monitor.Enter and Monitor.Exit expansion with its try/finally and lockTaken flag, re-entrancy on the same thread, and why this, Type objects and strings are bad targets.
Show you can find a hung lock: a lock held across slow work, an externally reachable target, inconsistent order between two locks, and how a dump or a TryEnter timeout exposes it.
Talk about where locks belong in a codebase: a small number of private lock objects with documented ownership, and review rules that keep callbacks and I/O out of locked regions.
## What the compiler generates The C# `lock` statement is shorthand for a pair of calls on `System.Threading.Monitor`. When the target is an ordinary reference-type expression, Microsoft's language reference gives the exact expansion: ```csharp object __lockObj = x; bool __lockWasTaken = false; try { System.Threading.Monitor.Enter(__lockObj, ref __lockWasTaken); // the body of the lock statement } finally { if (__lockWasTaken) System.Threading.Monitor.Exit(__lockObj); } ``` Read it in order: 1. The target expression is evaluated **once** and stored, so reassigning the field inside the body does not change which object gets released. 2. `Monitor.Enter` runs **inside** the `try`, and its `ref bool` overload sets the flag only when the lock is really acquired. 3. The `finally` calls `Monitor.Exit` only when the flag is true, so an exception in the body releases the lock, and a failed enter never calls `Exit` on a lock it does not hold (which would throw `SynchronizationLockException`). ## What a lock gives you, and what it does not - **Mutual exclusion per object.** Only one thread at a time runs code that locks the *same instance*. Two different objects are two different locks. - **Re-entrancy.** The thread that already holds the lock can enter it again (a locked method calling another locked method on the same object does not deadlock); the lock is free once every enter has been matched by an exit. - **Blocking.** Other threads wait inside `Monitor.Enter`; a waiting thread does nothing else. `Monitor.TryEnter` with a timeout is the variant that can give up. - **Visibility.** Microsoft's documentation describes `lock` as providing mutual exclusion and memory barriers, so state written inside one locked block is seen by the next thread that takes the same lock. - **No protection for code that skips it.** A method that reads the field without taking the lock can still see a half-finished update. Every read and write of the guarded state goes through the same lock. The target must be a reference type. `int n = 0; lock (n) { }` does not compile: error CS0185, "'int' is not a reference type as required by the lock statement". (Even if it were boxed, each call would lock a fresh box, so no two threads would ever share it.) ## Choosing the lock object | Target | What goes wrong | |---|---| | `this` | Any caller holding a reference can also `lock` it, so unrelated code contends for, or deadlocks on, your lock | | `typeof(Foo)` or another `Type` | Any code can obtain the same `Type` object through `typeof` or reflection | | a string, including a literal | Literals are interned, so every `lock ("orders")` in the process shares one object | | a public field or property | Outside code can lock it, or replace it so two threads lock different objects | | `private readonly object _gate = new()` | Nothing outside the class can reach it; this is the recommended shape | Use **one lock per piece of state that must stay consistent**, and do not reuse the same lock object for unrelated resources: Microsoft's guidance warns that sharing one instance across resources invites contention and deadlock. ## What goes inside the block The point of a lock is to make a **check and its update** one step. In a rate limiter, "is there budget left?" and "spend one unit" must happen together; if they are two separate locked blocks, two threads can both see one unit left and both spend it. Keep the body short: - read and write the guarded fields, nothing slower; - do not raise events or call delegates passed in by callers while holding the lock, because that code may take other locks in an order you cannot see; - do not do I/O inside a `lock`; in an `async` method the compiler forbids `await` there anyway (error CS1996), and asynchronous code uses a different primitive. ## Diagnosing a stuck lock When requests hang, the usual C#-level causes are a lock held across slow work, two locks taken in opposite orders by two code paths, or a lock target that outside code also locks. Replacing `lock` with `Monitor.TryEnter(_gate, timeout)` temporarily, or capturing a dump and looking for threads parked in `Monitor.Enter`, shows which object they are waiting on. The general theory of lock ordering belongs with mutual exclusion in general; the C#-specific fix is almost always a private lock object and a shorter body.
- Why does the generated code call Monitor.Enter inside the try and pass a bool by ref?Entering inside the `try` leaves no gap between acquiring the lock and having the `finally` in place. The `ref bool` overload sets the flag only when the lock is actually taken, so the `finally` calls `Monitor.Exit` only for a lock this thread holds; calling `Exit` without holding the lock throws `SynchronizationLockException`.
- Is a C# lock re-entrant, and what does that mean for one locked method calling another on the same object?Yes. The thread that holds the lock can enter it again, so the inner `lock (_gate)` succeeds immediately and the lock is released only when the outer block exits. The catch: the inner method may run while the outer one has the guarded state half updated, so re-entrancy does not make that intermediate state safe to read.
- Does a lock around writes protect a method that reads the same field without locking?No. The lock only excludes code that takes the same lock. An unlocked reader can observe a partially applied multi-field update or a stale value. Take the lock in the reader too; only when the state is one field can a single atomic read such as `Volatile.Read` or `Interlocked.Read` replace it.
- lock (this) is fine because the object owns the state it guards.
- Locking on a string literal gives each class its own private lock.
- An exception thrown inside a lock body leaves the lock held.
- A thread deadlocks if it locks an object it already holds.
- A lock around the writes also protects readers that skip the lock.
- You can lock on an int counter directly.