Use lock for a short synchronous critical section. Use Monitor directly when synchronous acquisition needs an explicit timeout. Use a one-permit SemaphoreSlim when the protected operation must continue across await. The key difference is who owns the gate and how acquisition waits.
This tutorial tests that choice with three standalone console programs: a deliberate compiler rejection, a synchronous ownership test, and an async fix with cancellation and fault checks. The examples target .NET 10. The System.Threading.Lock type used below requires .NET 9 and C# 13 or later. Sources and examples were verified on November 4, 2026.
Choose by the operation you need to protect
| Choice | Acquisition and ownership | Use it for |
|---|---|---|
lock |
Synchronous; the owning thread can reenter. Scope exit releases the gate. | A short block without await. |
Monitor.TryEnter |
Synchronous, with a timed attempt; the acquiring thread must release it. | A bounded attempt to enter an object monitor. |
SemaphoreSlim(1, 1) |
WaitAsync can wait asynchronously; there is no enforced thread or task owner. |
One operation at a time, including across await. Your code must pair acquisition and release. |
The C# lock reference distinguishes two implementations: a gate statically typed as System.Threading.Lock uses EnterScope; another reference-type gate uses Monitor.Enter and Monitor.Exit in a try/finally. Both release on scope exit, including exceptions. Do not assume every modern lock statement uses Monitor. Keep one dedicated gate for the shared state and use it consistently.
Monitor has thread affinity. By contrast, SemaphoreSlim does not enforce thread or task identity. That permits an async continuation to release a permit, but also means an unrelated caller can release one incorrectly. Its name does not make it an automatically managed async lock.
First, verify why await inside lock fails
This complete program intentionally fails compilation. It never runs:
using System.Threading.Tasks;
object gate = new();
lock (gate)
{
await Task.Delay(1);
}
The observed diagnostic is:
error CS1996: Cannot await in the body of a lock statement
The language forbids await inside lock. Replacing the statement with manual Monitor calls around an await would lose that compiler protection while retaining Monitor’s thread ownership requirement. The continuation is not guaranteed to run on the acquiring thread. Choose the gate for the operation rather than bypassing the diagnostic.
Use lock for scope cleanup, Monitor for timed entry
The next program deliberately holds an object monitor while a different, dedicated thread attempts entry. The contender times out and demonstrates that it cannot release the owner’s monitor. After the owner leaves its lock, a new timed acquisition succeeds. The final phase uses a separate System.Threading.Lock to protect 4,000 synchronous increments.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
object monitorGate = new();
bool timedOut = false;
bool wrongOwnerRejected = false;
lock (monitorGate)
{
var contender = new Thread(() =>
{
bool taken = false;
try
{
Monitor.TryEnter(monitorGate, 25, ref taken);
timedOut = !taken;
if (taken) throw new Exception("Unexpected acquisition");
try { Monitor.Exit(monitorGate); }
catch (SynchronizationLockException) { wrongOwnerRejected = true; }
}
finally
{
if (taken) Monitor.Exit(monitorGate);
}
}) { IsBackground = true };
contender.Start();
if (!contender.Join(5000)) throw new TimeoutException("Contender did not finish");
}
if (!timedOut || !wrongOwnerRejected) throw new Exception("Ownership test failed");
bool acquired = false;
try
{
Monitor.TryEnter(monitorGate, 100, ref acquired);
if (!acquired) throw new Exception("Monitor was not released");
}
finally
{
if (acquired) Monitor.Exit(monitorGate);
}
Console.WriteLine("Monitor: timeout, wrong-owner rejection, reacquisition passed");
var gate = new System.Threading.Lock();
int count = 0;
using var budget = new CancellationTokenSource(TimeSpan.FromSeconds(20));
Task[] workers = Enumerable.Range(0, 4).Select(_ => Task.Run(() =>
{
for (int i = 0; i < 1000; i++)
{
budget.Token.ThrowIfCancellationRequested();
lock (gate) { count++; }
}
})).ToArray();
await Task.WhenAll(workers);
if (count != 4000) throw new Exception("Lost update");
Console.WriteLine("Lock: 4000 protected increments passed");
Expected stdout:
Monitor: timeout, wrong-owner rejection, reacquisition passed
Lock: 4000 protected increments passed
TryEnter’s ref-bool overload starts with taken = false. Only a successful acquisition allows the protected work and requires Monitor.Exit in finally. The 25-millisecond attempt avoids an infinite wait; it is not a precise timing assertion. Monitor’s timeout overload does not take a cancellation token.
The Join inside the first lock is test orchestration: it keeps the owner holding the monitor until the contender finishes its bounded attempt. Do not copy that dependency into normal application work. The five-second join is a test failure bound, and the contender is a background thread. The increment phase checks a 20-second cancellation budget between operations; it does not make a blocked lock acquisition cancellable.
For the separate problem of acquiring two resources, see reproducing a two-lock deadlock and fixing lock ordering. A timeout provides a failure path; your application still needs to decide whether to report failure, retry, or abandon the operation.
Use one semaphore permit across await
Here the entire read, asynchronous yield, and write must be exclusive. A single shared SemaphoreSlim(1, 1) protects that whole operation. Acquisition happens before the try: if waiting is canceled, the caller never enters the release block. Once acquisition succeeds, finally returns exactly one permit even when the operation throws.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using var gate = new SemaphoreSlim(1, 1);
using var budget = new CancellationTokenSource(TimeSpan.FromSeconds(20));
CancellationToken token = budget.Token;
int count = 0;
async Task Increment(CancellationToken cancellation, bool fail = false)
{
await gate.WaitAsync(cancellation);
try
{
int before = count;
await Task.Yield();
cancellation.ThrowIfCancellationRequested();
if (fail) throw new InvalidOperationException("Injected failure");
count = before + 1;
}
finally { gate.Release(); }
}
await gate.WaitAsync(token);
try
{
// A second acquisition cannot reenter this one-permit semaphore.
if (await gate.WaitAsync(25, token))
{
gate.Release();
throw new Exception("Unexpected nested acquisition");
}
using var canceled = CancellationTokenSource.CreateLinkedTokenSource(token);
Task waiting = Increment(canceled.Token);
canceled.Cancel();
try { await waiting; throw new Exception("Cancellation was ignored"); }
catch (OperationCanceledException) when (canceled.IsCancellationRequested) { }
if (gate.CurrentCount != 0) throw new Exception("Waiter released owner's permit");
}
finally { gate.Release(); }
Console.WriteLine("SemaphoreSlim: nested wait timed out; canceled waiter released nothing");
try { await Increment(token, fail: true); throw new Exception("Failure was ignored"); }
catch (InvalidOperationException ex) when (ex.Message == "Injected failure") { }
if (gate.CurrentCount != 1 || count != 0) throw new Exception("Fault leaked a permit");
Console.WriteLine("SemaphoreSlim: fault cleanup passed");
for (int round = 0; round < 20; round++)
{
Task[] workers = Enumerable.Range(0, 4).Select(async _ =>
{
for (int i = 0; i < 20; i++) await Increment(token);
}).ToArray();
await Task.WhenAll(workers);
}
if (count != 1600 || gate.CurrentCount != 1) throw new Exception("Async gate failed");
Console.WriteLine("SemaphoreSlim: 1600 protected async increments passed");
Expected stdout:
SemaphoreSlim: nested wait timed out; canceled waiter released nothing
SemaphoreSlim: fault cleanup passed
SemaphoreSlim: 1600 protected async increments passed
The first phase holds the only permit and tries to acquire another. The nested wait times out: this gate does not provide the owning-thread reentry that lock provides. An async call chain that recursively acquires the same one-permit semaphore can therefore wait on itself. Keep the acquisition boundary at the outer operation and avoid reacquiring it in helpers.
The cancellation check starts a waiter while the permit is unavailable, then cancels that waiter and verifies the owner’s permit remains held. The injected exception tests cleanup after successful acquisition. Finally, twenty rounds of four workers perform twenty increments each. Task.Yield creates an asynchronous suspension between reading and writing, and the final assertions check both the total of 1,600 and the restored permit count. These are correctness checks, not a throughput benchmark or a proof for every possible schedule.
The cancellation token passed to WaitAsync controls waiting. It does not automatically cancel work after admission: the operation also checks it before committing its update. All workers are awaited before the semaphore is disposed. Microsoft’s SemaphoreSlim documentation requires other operations to finish before disposal and makes permit pairing the caller’s responsibility.
Run each program separately
Create a console project with a .NET 10 SDK, replace its Program.cs with one complete program above, and run it. Repeat with each program; the first should report CS1996 and the other two should print their expected output.
dotnet new console --framework net10.0 --name GateDemo
cd GateDemo
dotnet run
For application code, store the gate with the state it protects. Creating a new semaphore per invocation would give each caller an independent permit and would not serialize access. If you need several independent operations in flight, see SemaphoreSlim for bounded asynchronous work. For exclusive access across an await, keep the maximum count at one and preserve the acquisition-and-release boundary shown here.