2.18 — Thread Safety: lock, SemaphoreSlim, Interlocked, volatile¶
← Roadmap · Section: 2. Collections, LINQ and Async Prev: 2.17 IAsyncEnumerable · Next: 2.19 Parallel programming
Markers: ⭐ ⚠️ · Confidence: 🔴 · Last reviewed: —
TL;DR¶
Thread safety means your code still gives the right answer when several threads run it at the same time. Nothing in C# is thread-safe automatically — you have to make it so.
lockis the default tool. Simple, fast, covers most cases — but you cannotawaitinside it.SemaphoreSlimis the async-friendly alternative, because it hasWaitAsync.Interlockedupdates a single number atomically with no lock at all — much faster when it fits.- The real answer in ASP.NET Core is usually do not share mutable state at all.
Definitions¶
Every term this note uses, and — importantly — what kind of C# thing each one actually is.
| Term | What it is in C# | What it means |
|---|---|---|
| Thread safe | a property of your code | Several threads can run it at once and the result is still correct. |
| Race condition | a bug, not an API | The result depends on which thread happens to win. Works in testing, fails under load. |
| Atomic | a property of an operation | It cannot be interrupted halfway. Other threads see it as either not started or completely done — never partly done. |
| Critical section | a block of code | Code that only one thread may be inside at a time. |
| Mutual exclusion | a guarantee | The rule that enforces a critical section: one in, everyone else waits. |
lock |
a C# keyword | Marks a critical section. lock (x) { ... } compiles into Monitor.Enter(x) and Monitor.Exit(x) wrapped in a try/finally. |
Monitor |
a static class in System.Threading |
What lock actually calls underneath. You rarely write it by hand. |
SemaphoreSlim |
a class you create with new |
Holds a count of permits. Lets N threads through and makes the rest wait. Uniquely, it has an async wait (WaitAsync). |
Interlocked |
a static class in System.Threading |
Methods that read-modify-write a number as one single CPU instruction, so no lock is needed. |
volatile |
a field modifier, like readonly |
Tells the compiler and CPU never to cache this field in a register. Every read goes to real memory. |
| Thread affinity | a property of a lock | The lock must be released by the same thread that took it. This is exactly why await inside lock is banned. |
| Deadlock | a bug | Two threads each holding a lock the other one needs. Neither can ever continue. |
The three you will actually type are lock, SemaphoreSlim and Interlocked. volatile
is included because it gets asked about, not because you should use it.
The concept¶
count++ looks like one instruction. It is three:
- Read the current value from memory
- Add one to it
- Write the result back
Two threads running that at the same time can interleave:
| Thread A | Thread B | count |
|
|---|---|---|---|
| 1 | reads 5 | 5 | |
| 2 | reads 5 | 5 | |
| 3 | computes 6 | 5 | |
| 4 | computes 6 | 5 | |
| 5 | writes 6 | 6 | |
| 6 | writes 6 | 6 |
Two increments, one result. That is a race condition — the outcome depends on timing, so it works in testing and fails occasionally under load.
The picture: two people updating the same paper tally. Both read "5", both cross it out and write "6". One increment is silently lost. The fix is that only one person may hold the pen at a time.
How it works¶
lock — one thread at a time¶
private readonly object _gate = new();
private int _count;
public void Increment()
{
lock (_gate) // only one thread inside this block at any moment
{
_count++;
}
}
Rules that matter:
lock (this) // ✗ BAD — external code can lock on your instance too
lock (typeof(MyClass)) // ✗ BAD — shared across the whole app domain
lock ("some string") // ✗ BAD — string literals are interned and shared
lock (_gate) // ✓ a private readonly object, used only for this
Always lock on a private readonly object that exists only to be a lock. Locking on anything publicly reachable means unrelated code can deadlock you.
.NET 9 added a dedicated System.Threading.Lock type which is faster and clearer:
⚠️ You cannot await inside a lock¶
The compiler blocks it, and rightly so. A lock is tied to a specific thread — it must be
released by the same thread that took it. After an await, your code may resume on a
different thread, which could not release the lock. Deadlock.
SemaphoreSlim — the async-safe lock¶
private readonly SemaphoreSlim _gate = new(1, 1); // 1 = acts like a lock
public async Task UpdateAsync(Order order, CancellationToken ct)
{
await _gate.WaitAsync(ct);
try
{
await _db.SaveAsync(order, ct); // await IS allowed here
}
finally
{
_gate.Release(); // MUST be in finally
}
}
The (1, 1) means "initially 1 slot free, maximum 1 slot" — so it behaves like a mutex.
Larger numbers make it a throttle:
The finally is not optional. If an exception escapes without releasing, that slot is
gone forever and every future caller blocks. That is a total, permanent hang — a genuinely
nasty production bug.
Interlocked — atomic without locking¶
For simple numeric updates, the CPU can do it in one instruction:
private int _count;
Interlocked.Increment(ref _count); // ++ atomically
Interlocked.Decrement(ref _count);
Interlocked.Add(ref _count, 5);
Interlocked.Exchange(ref _count, 0); // set, returning the old value
// Set only if it currently equals the expected value
Interlocked.CompareExchange(ref _count, newValue, expectedValue);
Much faster than a lock — no blocking, no context switches. Use it whenever your shared state is a single number or reference. It cannot help with anything more complex.
volatile — usually not what you want¶
volatile prevents the compiler and CPU from caching or reordering reads of a field:
private volatile bool _stopping;
// Thread A
_stopping = true;
// Thread B
while (!_stopping) { DoWork(); } // without volatile, may never see the change
Without volatile, the JIT may hoist _stopping into a register and loop forever on a stale
value.
But volatile does not make operations atomic. _count++ on a volatile field is still
three steps and still races.
In practice you rarely want it. For a stop flag, use CancellationToken
(2.14). For counters, use Interlocked. volatile is for
lock-free algorithms, which almost nobody should be writing.
Choosing¶
| Situation | Use |
|---|---|
| Simple counter or flag swap | Interlocked |
| Short synchronous critical section | lock |
Critical section containing await |
SemaphoreSlim.WaitAsync |
| Limiting concurrency to N | SemaphoreSlim(n, n) |
| Shared collection | A concurrent collection (2.3) |
| Anything else | Restructure so nothing is shared |
The best answer: do not share¶
In ASP.NET Core, most thread-safety problems come from state that should never have been shared. The framework already gives you the tools to avoid it:
// PROBLEM — a singleton holding mutable state needs locking everywhere
public class OrderService
{
private List<Order> _pending = new(); // shared across ALL requests
}
// SOLUTION — scoped lifetime means one instance per request.
// No sharing, so no locking needed at all.
builder.Services.AddScoped<OrderService>();
Scoped services are the answer to most of this. Each request gets its own instance, so there is nothing to race over. Reserve singletons for things that are genuinely stateless or genuinely designed for concurrency. See 6.3.
Code¶
A rate limiter using SemaphoreSlim as a throttle:
public class ApiClient(HttpClient http) : IDisposable
{
// Allow at most 5 concurrent outbound calls
private readonly SemaphoreSlim _throttle = new(5, 5);
public async Task<T?> GetAsync<T>(string url, CancellationToken ct)
{
await _throttle.WaitAsync(ct);
try
{
return await http.GetFromJsonAsync<T>(url, ct);
}
finally
{
_throttle.Release(); // ALWAYS, even on exception or cancellation
}
}
public void Dispose() => _throttle.Dispose();
}
And the Interlocked version of a metrics counter, which needs no lock at all:
public class RequestCounter
{
private long _total;
private long _failed;
public void RecordSuccess() => Interlocked.Increment(ref _total);
public void RecordFailure()
{
Interlocked.Increment(ref _total);
Interlocked.Increment(ref _failed);
}
// Reading a long is NOT atomic on 32-bit systems, so read it properly
public (long Total, long Failed) Snapshot() =>
(Interlocked.Read(ref _total), Interlocked.Read(ref _failed));
}
⚠️ Note that the two increments in RecordFailure are individually atomic but not atomic
together — a reader could see _total updated and _failed not yet. For metrics that is
acceptable. If it were not, you would need a lock.
Interview questions¶
Q: Why is count++ not thread-safe?
Because it is three separate operations: read the value, add one, write it back. Two threads
can both read the same starting value before either writes, so both compute the same result
and one increment is lost. The failure depends entirely on timing, which is why it passes
tests and fails intermittently under production load. Interlocked.Increment fixes it by
doing the whole read-modify-write as a single atomic CPU instruction.
Q: Why can't you await inside a lock?
Because a lock has thread affinity — it must be released by the same thread that acquired it.
After an await, the continuation can resume on a completely different thread, which would
then try to release a lock it does not own. The compiler rejects it outright rather than
letting you create that deadlock. When you need mutual exclusion around async work you use
SemaphoreSlim with WaitAsync, because a semaphore is not tied to a thread.
Q: What should you lock on?
A private readonly object that exists solely as a lock. Locking on this, on a type, or on a
string literal is dangerous because those are all reachable from outside your class — other
code can take the same lock and deadlock you in ways that are extremely hard to trace. String
literals are especially bad because they are interned, so two unrelated classes locking on
the same literal share a lock. In .NET 9 there is a dedicated System.Threading.Lock type
which is both clearer and faster.
Q: What is the best way to handle shared state in ASP.NET Core?
Usually to not have any. Most thread-safety problems there come from putting mutable state in
a singleton, which is then shared across every concurrent request. Registering the service as
scoped gives each request its own instance and the problem disappears entirely — no locks, no
races, nothing to reason about. I would only reach for synchronisation primitives when state
genuinely must be shared, like a cache or a counter, and even then a ConcurrentDictionary
or Interlocked usually beats a hand-written lock.
Traps ⚠️¶
- Locking on
this, a type, or a string literal. All publicly reachable, all can deadlock you from outside. - Forgetting
Release()in afinally. One leaked semaphore slot hangs every future caller permanently. volatiledoes not make operations atomic. It only prevents caching and reordering.- Two atomic operations are not atomic together. A reader can see a half-updated pair.
- Holding a lock while doing I/O serialises your whole application on that call.
- Nested locks in different orders deadlock. Always take locks in a consistent order.
lockin an async method is a compile error — butMonitor.Enteraround anawaitis not, and it is a real deadlock. Do not work around the compiler.longreads and writes are not atomic on 32-bit platforms. UseInterlocked.Read.
Related¶
- 2.3 Concurrent collections — usually a better answer than locking
- 2.10 Threads vs Tasks — where concurrency comes from
- 2.14 CancellationToken — the right way to signal "stop"
- 2.19 Parallel programming — where these problems multiply
- 1.5 static — static state is shared state
- 6.3 Service lifetimes — scoped services avoid the problem