Why does C# reject await inside a lock statement, and how do you protect shared state across an await with SemaphoreSlim?
answer
- who owns the lock
- the continuation may resume elsewhere
- rejected at compile time
- count of one, WaitAsync
- Release in finally
basics
~20 sA lock belongs to the thread that took it, and code after an await may resume on another thread, so C# rejects await inside lock with error CS1996. Use SemaphoreSlim(1, 1): await WaitAsync(), then Release() in a finally.
solid answer
~50 s`lock` is built on a thread-owned lock: the same thread must enter and exit it. After an `await` that suspends, the rest of the method runs as a continuation, often on a different thread, so the exit could not be guaranteed to happen on the owner; the compiler refuses with CS1996, "Cannot await in the body of a lock statement". For exclusive access across an `await`, use `SemaphoreSlim` with an initial and maximum count of 1: `await _gate.WaitAsync();` then `try { ... } finally { _gate.Release(); }`. `WaitAsync` waits without blocking a thread, and `SemaphoreSlim` has no thread affinity, so any thread may call `Release`. The trade-offs: it is not re-entrant, so a nested `WaitAsync` on the same semaphore waits forever, nothing stops the wrong code from releasing it, and releasing past the maximum throws `SemaphoreFullException`.
code
csharp · 16 linesvar cache = new ConfigCache();
await cache.RefreshAsync();
class ConfigCache
{
private readonly object _gate = new();
private string _json = "";
public async Task RefreshAsync()
{
lock (_gate)
{
_json = await File.ReadAllTextAsync("config.json");
}
}
}go deeper
Recall that the compiler forbids await inside lock, and that async code guards shared state with SemaphoreSlim(1, 1), WaitAsync and Release in a finally.
Explain why: Monitor is thread-owned and continuations may resume on another thread. Know where WaitAsync goes relative to try, and what a timed WaitAsync returning false means.
Diagnose the failures that remain: a nested WaitAsync deadlocking on itself, an extra Release throwing SemaphoreFullException, and ReaderWriterLockSlim exited on a continuation thread.
Argue the cost side: an await inside a guarded region makes every caller wait on that I/O, so push for designs that shrink the region rather than standardising on a bigger lock.
## Why the compiler refuses The `lock` statement expands to `Monitor.Enter` and `Monitor.Exit` (or, for a `System.Threading.Lock` target in C# 13 and later, `EnterScope` and a `Dispose`). Both are **thread-owned locks**: Microsoft's documentation states that because `Monitor` has thread affinity, the thread that acquired the lock must release it. An `await` breaks that assumption. When the awaited task is not yet complete, the method returns to its caller and the rest of its body is scheduled as a **continuation**. In a console app or a web server that continuation usually runs on a thread-pool thread, which need not be the one that started the method. If C# allowed `await` inside `lock`, the `finally` that calls `Monitor.Exit` could run on a thread that never entered. So the compiler stops it outright: - error **CS1996**: "Cannot await in the body of a lock statement". Doing the same thing by hand compiles but fails at run time. Calling `Monitor.Enter(gate)`, then `await Task.Delay(50)`, then `Monitor.Exit(gate)` in a console app resumed on thread 5 after starting on thread 1, and `Monitor.Exit` threw **`SynchronizationLockException`**. Where a continuation *does* return to the same thread (a UI thread), the problem changes shape rather than going away: while the method is suspended, other work on that thread can re-enter the re-entrant lock. ## SemaphoreSlim as an async lock `SemaphoreSlim` counts permits rather than tracking an owner. Created with `new SemaphoreSlim(1, 1)`, it admits one caller at a time, and its `WaitAsync` method returns a task that completes when a permit is granted, so a waiting caller holds no thread. The pattern for a configuration cache that must reload from disk while holding exclusive access: 1. `await _gate.WaitAsync();` **before** the `try`, so a failed or cancelled wait never reaches `Release`. 2. Do the work, including any `await`, inside the `try`. 3. Call `_gate.Release();` in the `finally`, so an exception still frees the permit. ```csharp await _gate.WaitAsync(cancellationToken); try { _json = await File.ReadAllTextAsync(path, cancellationToken); } finally { _gate.Release(); } ``` `WaitAsync` has overloads that take a `CancellationToken`, a timeout, or both; the timeout versions return `Task<bool>`, and `false` means the permit was not acquired, so `Release` must not be called. ## What SemaphoreSlim does not do - **It is not re-entrant.** A method holding the permit that calls a helper which also awaits `WaitAsync` on the same semaphore waits on itself forever; a timed `WaitAsync(TimeSpan.FromMilliseconds(200))` in that position returns `false`. Split the work into a public method that takes the semaphore and private methods that assume it is held. - **It has no owner.** Microsoft's documentation states that semaphores do not enforce thread identity on wait and release, which is what makes it usable across `await`, and also means a stray `Release` from unrelated code is accepted. - **Over-release throws.** Releasing past the maximum count of 1 throws `SemaphoreFullException`. - **No fairness.** The documentation says no guaranteed order, such as first-in first-out, governs which waiter enters next. - **It is disposable.** It implements `IDisposable`; a long-lived field usually lives as long as the object that owns it. ## Comparing the options | | `lock` / `Monitor` | `SemaphoreSlim(1, 1)` | `ReaderWriterLockSlim` | |---|---|---|---| | `await` inside | error CS1996 | allowed | compiles, but exiting on another thread throws | | Thread affinity | yes | no | yes | | Re-entrant | yes | no | no by default (`NoRecursion`) | | Waits without a thread | no | yes, with `WaitAsync` | no | | Concurrent readers | no | no | yes | `ReaderWriterLockSlim` looks attractive for a read-mostly cache, but it is thread-owned like `Monitor`: entering a read lock, awaiting, and calling `ExitReadLock` on the continuation threw `SynchronizationLockException`. It belongs around synchronous sections only. ## When to reach for which - A short synchronous critical section: keep `lock`; it is cheaper and re-entrant. - Exclusive access that must span an `await`: `SemaphoreSlim(1, 1)` with `WaitAsync` and `try`/`finally`. - A larger initial count to cap how many operations run at once is a different job, throttling rather than locking, and belongs with combining tasks. Whichever you choose, keep the guarded region as small as the invariant allows: an `await` inside it means every other caller waits for that I/O too.
- What happens when a method holding a SemaphoreSlim(1, 1) calls a helper that awaits WaitAsync on the same semaphore?The helper waits for a permit its own caller holds, so the flow deadlocks on itself: `SemaphoreSlim` counts permits and has no notion of an owner. With a timeout the call returns `false` instead. Restructure so only the outer method acquires the semaphore and private helpers assume it is held.
- Why not call Monitor.Enter before the await and Monitor.Exit after it by hand?It compiles, but `Monitor` is thread-owned. In a console app or server the continuation usually resumes on a thread-pool thread, and `Monitor.Exit` there throws `SynchronizationLockException`. Even when it resumes on the same thread, other work on that thread can re-enter the lock while the method is suspended.
- Can ReaderWriterLockSlim give async code concurrent readers across an await?No. `ReaderWriterLockSlim` has thread affinity like `Monitor`: a read lock entered before an `await` and exited on the continuation thread throws `SynchronizationLockException`. Use it only around synchronous sections; across `await`, `SemaphoreSlim` is the tool, at the cost of serialising readers.
- await inside lock is fine as long as the awaited call is fast.
- SemaphoreSlim(1, 1) is re-entrant, so nested WaitAsync calls succeed.
- Monitor.Exit after an await works because an async method keeps its thread.
- WaitAsync blocks a thread-pool thread until the permit is free.
- Release can sit after the try block; finally is optional here.