Race conditions
suggest changeA race condition is a bug where the result depends on the timing of threads (or async continuations) that touch shared state. The code works in tests, works on your machine, and then fails now and then in production, because the threads happened to interleave differently.
Most races in C# have one of these shapes:
- Lost update (read-modify-write).
counter++,balance -= amountandlist.Add(x)are several steps. Two threads can read the same old value and one write overwrites the other. - Check-then-act.
if (!dict.ContainsKey(k)) dict.Add(k, v): the condition can stop being true between the check and the action. - Visibility. One thread sets a flag, another thread never sees the change because the JIT kept the value in a register.
- Torn reads. A struct larger than a pointer is copied in several pieces, so a reader can see half of the old value and half of the new one.
The fixes are Interlocked, lock, SemaphoreSlim, concurrent collections, volatile, immutable data, or (best) not sharing mutable state at all.
The examples are .NET 10 / C# 14 file-based programs. Run them with dotnet run -c Release app.cs. Some races only show up with JIT optimizations on, and file-based programs build in Debug by default. All output below comes from real runs on Windows. Your numbers will differ, and they change from one run to the next, which is the point.
Lost updates: counter++
Four threads each increment a shared counter a million times:
int counter = 0;
void Work()
{
for (int i = 0; i < 1_000_000; i++)
counter++;
}
for (int run = 1; run <= 5; run++)
{
counter = 0;
var threads = new Thread[4];
for (int t = 0; t < threads.Length; t++)
{
threads[t] = new Thread(Work);
threads[t].Start();
}
foreach (var t in threads) t.Join();
Console.WriteLine($"run {run}: counter = {counter:N0} (expected 4,000,000)");
}
run 1: counter = 1,124,802 (expected 4,000,000)
run 2: counter = 1,337,185 (expected 4,000,000)
run 3: counter = 1,942,913 (expected 4,000,000)
run 4: counter = 1,922,789 (expected 4,000,000)
run 5: counter = 1,661,234 (expected 4,000,000)
More than half of the increments are lost. counter++ compiles to three separate steps:
tmp = counter // 1. load
tmp = tmp + 1 // 2. add
counter = tmp // 3. store
When two threads interleave like this, one increment disappears:
Thread A Thread B counter
load (tmp = 41) 41
load (tmp = 41) 41
add (tmp = 42) 41
store (counter = 42) 42
add (tmp = 42) 42
store (counter = 42) 42 <- A's update is lost
This happens with any type, int included. Reads and writes of an int are atomic, but a read followed by a write is not.
Fix 1: Interlocked
System.Threading.Interlocked turns single-variable operations into one atomic CPU instruction (lock xadd, lock cmpxchg on x64). Here is the counter fixed two ways, compared with the broken version:
using System.Diagnostics;
const int Threads = 4;
const int Iterations = 1_000_000;
int plain = 0;
int interlocked = 0;
int locked = 0;
Lock gate = new();
Measure("counter++ ", () => plain++, () => plain);
Measure("Interlocked ", () => Interlocked.Increment(ref interlocked), () => interlocked);
Measure("lock (Lock) ", () => { lock (gate) locked++; }, () => locked);
static void Measure(string name, Action increment, Func<int> read)
{
var sw = Stopwatch.StartNew();
var threads = Enumerable.Range(0, Threads)
.Select(_ => new Thread(() => { for (int i = 0; i < Iterations; i++) increment(); }))
.ToArray();
foreach (var t in threads) t.Start();
foreach (var t in threads) t.Join();
Console.WriteLine($"{name} {read(),10:N0} {sw.ElapsedMilliseconds,4} ms");
}
counter++ 1,097,234 12 ms
Interlocked 4,000,000 75 ms
lock (Lock) 4,000,000 412 ms
Both fixes give the right answer. The broken version is fastest only because it's wrong. The timings bounce around a lot between runs, but the order stays the same: a heavily contended lock costs much more than an interlocked instruction.
The Interlocked methods you'll use most:
| Method | Does atomically |
|---|---|
Increment(ref x), Decrement(ref x) |
++x, --x, returns the new value |
Add(ref x, n) |
x += n, returns the new value |
Exchange(ref x, v) |
x = v, returns the old value |
CompareExchange(ref x, v, expected) |
if (x == expected) x = v, returns the old value |
Read(ref long) |
reads a 64-bit value atomically, even on 32-bit platforms |
And, Or |
bitwise flags (.NET 5+) |
CompareExchange is the building block for any other lock-free update. You read the current value, compute the new one, and retry if another thread changed the value in the meantime:
// Interlocked.CompareExchange: lock-free "update to maximum"
int max = 0;
void RecordValue(int value)
{
int current = Volatile.Read(ref max);
while (value > current)
{
int seen = Interlocked.CompareExchange(ref max, value, current);
if (seen == current) return; // we won: max is now value
current = seen; // someone else changed it: retry
}
}
Parallel.For(0, 1_000_000, i => RecordValue((int)(i * 7919L % 1_000_003)));
Console.WriteLine($"max = {max:N0}");
long total = 0;
Parallel.For(1, 100_001, i => Interlocked.Add(ref total, i));
Console.WriteLine($"total = {total:N0}");
int initialized = 0;
Parallel.For(0, 8, i =>
{
if (Interlocked.Exchange(ref initialized, 1) == 0)
Console.WriteLine($"iteration {i} did the one-time setup");
});
max = 1,000,002
total = 5,000,050,000
iteration 0 did the one-time setup
Interlocked.Exchange(ref flag, 1) == 0 is true for exactly one caller, which makes it a cheap "run once" guard. Which iteration wins varies between runs.
Interlocked works on one variable at a time. When an update touches two fields, or must keep an invariant (such as "Count matches the items in the array"), use a lock.
Fix 2: lock
lock makes a block of code mutually exclusive: only one thread at a time can be inside a block locked on the same object. Since C# 13 / .NET 9, the preferred lock object is System.Threading.Lock:
class Inventory
{
private readonly Lock _lock = new();
private readonly Dictionary<string, int> _stock = new();
private int _totalItems;
public bool TryRemove(string sku, int quantity)
{
lock (_lock)
{
if (!_stock.TryGetValue(sku, out int have) || have < quantity)
return false;
_stock[sku] = have - quantity;
_totalItems -= quantity; // both fields change together
return true;
}
}
}
Rules that prevent most locking bugs:
- Lock on a private,
readonlyobject that only exists for locking. Never uselock (this),lock (typeof(X))or a string, because outside code can lock on those too. - Every access to the shared data needs the lock, reads included. A lock only protects data from code that also takes it.
- Keep the locked region short, and don't call unknown code (events, callbacks, virtual methods) while holding it. That's how deadlocks happen.
- You can't
awaitinside alock(see the async section below).
See Lock Statement for more details.
Check-then-act
A race doesn't need arithmetic. Any time you test a condition and then act on it, the condition can change in between:
var keys = Enumerable.Range(0, 1000).Select(i => $"key{i % 50}").ToArray();
for (int run = 1; run <= 6; run++)
{
var cache = new Dictionary<string, int>();
try
{
Parallel.ForEach(keys, key =>
{
if (!cache.ContainsKey(key)) // check...
cache.Add(key, key.Length); // ...then act
});
Console.WriteLine($"run {run}: {cache.Count} entries (50 distinct keys)");
}
catch (AggregateException e)
{
Console.WriteLine($"run {run}: {e.InnerException!.GetType().Name}: {e.InnerException.Message}");
}
}
run 1: IndexOutOfRangeException: Index was outside the bounds of the array.
run 2: 50 entries (50 distinct keys)
run 3: 50 entries (50 distinct keys)
run 4: 50 entries (50 distinct keys)
run 5: 50 entries (50 distinct keys)
run 6: ArgumentException: An item with the same key has already been added. Key: key35
Two different bugs show up here:
- Two threads both see that
key35is missing and both callAdd. The second one throws. Dictionary<TKey,TValue>isn't thread-safe at all. Concurrent writes corrupt its internal arrays, which shows up asIndexOutOfRangeExceptionorInvalidOperationException: Operations that change non-concurrent collections must have exclusive access. In other runs a corrupted dictionary reported 53 entries for 50 keys, and callingClear()on it crashed.
Most runs succeed, and that's what makes races dangerous: a test that passes 4 times out of 6 looks like it works.
The same is true for List<T>. Add is a read-modify-write of the internal array and the count:
for (int run = 1; run <= 4; run++)
{
var list = new List<int>();
try
{
Parallel.For(0, 100_000, i => list.Add(i));
Console.WriteLine($"run {run}: list.Count = {list.Count:N0}");
}
catch (AggregateException e)
{
Console.WriteLine($"run {run}: {e.InnerException!.GetType().Name}: {e.InnerException.Message}");
}
}
run 1: list.Count = 17,420
run 2: list.Count = 8,203
run 3: list.Count = 13,816
run 4: list.Count = 8,200
Most of the 100,000 items are silently lost. In other runs Add threw ArgumentException: Source array was not long enough while two threads were growing the internal array at the same time.
The fixes are a lock around every access, a concurrent collection, or letting the library collect the results for you:
using System.Collections.Concurrent;
var bag = new ConcurrentBag<int>();
Parallel.For(0, 100_000, i => bag.Add(i));
Console.WriteLine($"ConcurrentBag: {bag.Count:N0}");
var list = new List<int>();
var gate = new Lock();
Parallel.For(0, 100_000, i => { lock (gate) list.Add(i); });
Console.WriteLine($"List + lock: {list.Count:N0}");
long[] squares = Enumerable.Range(0, 100_000).AsParallel().AsOrdered().Select(i => (long)i * i).ToArray();
Console.WriteLine($"PLINQ ToArray: {squares.Length:N0}, squares[99_999] = {squares[99_999]:N0}");
ConcurrentBag: 100,000
List + lock: 100,000
PLINQ ToArray: 100,000, squares[99_999] = 9,999,800,001
Concurrent collections don't make your code atomic
Every single method of ConcurrentDictionary is thread-safe, but a sequence of calls is not. This word counter still loses updates:
using System.Collections.Concurrent;
string[] words = Enumerable.Range(0, 400_000).Select(i => (i % 4) switch
{
0 => "apple", 1 => "banana", 2 => "cherry", _ => "date",
}).ToArray();
// Wrong: each call is thread-safe, but read + write is not atomic
var racy = new ConcurrentDictionary<string, int>();
Parallel.ForEach(words, w =>
{
racy.TryGetValue(w, out int n);
racy[w] = n + 1;
});
Console.WriteLine("racy: " + Format(racy));
// Right: AddOrUpdate retries until its update wins
var counts = new ConcurrentDictionary<string, int>();
Parallel.ForEach(words, w => counts.AddOrUpdate(w, 1, (_, n) => n + 1));
Console.WriteLine("AddOrUpdate: " + Format(counts));
static string Format(ConcurrentDictionary<string, int> d) =>
string.Join(", ", d.OrderBy(kv => kv.Key).Select(kv => $"{kv.Key}={kv.Value:N0}"));
racy: apple=82,945, banana=84,383, cherry=17,995, date=84,867
AddOrUpdate: apple=100,000, banana=100,000, cherry=100,000, date=100,000
Use the compound methods: GetOrAdd, AddOrUpdate, TryAdd, TryRemove, TryUpdate (a compare-and-swap on a value).
There is one more catch. GetOrAdd(key, factory) and AddOrUpdate run the delegate outside the dictionary's internal lock. Several threads can run the factory for the same key at the same time. Only one result is stored, but the work (and its side effects) can happen several times:
using System.Collections.Concurrent;
int factoryCalls = 0;
var cache = new ConcurrentDictionary<string, string>();
string Load(string key)
{
Interlocked.Increment(ref factoryCalls);
Thread.Sleep(50); // pretend this is expensive
return $"config for {key}";
}
Parallel.For(0, 8, _ => cache.GetOrAdd("db", Load));
Console.WriteLine($"GetOrAdd: factory ran {factoryCalls} times, {cache.Count} entry");
factoryCalls = 0;
var lazyCache = new ConcurrentDictionary<string, Lazy<string>>();
Parallel.For(0, 8, _ =>
{
string value = lazyCache.GetOrAdd("db", k => new Lazy<string>(() => Load(k))).Value;
});
Console.WriteLine($"GetOrAdd(Lazy): factory ran {factoryCalls} times, {lazyCache.Count} entry");
GetOrAdd: factory ran 8 times, 1 entry
GetOrAdd(Lazy): factory ran 1 times, 1 entry
Wrapping the value in Lazy<T> fixes it. Creating extra Lazy objects is cheap, only one of them gets stored, and Lazy<T> (thread-safe by default) runs the expensive factory exactly once. The same idea gives you thread-safe singletons, see Lazy thread-safe Singleton using Lazy<T>.
Races in async code
async code runs on thread pool threads, and continuations of different operations can run at the same time. On top of that, every await is a point where other code can run and change state, even when only one thread is involved. This withdraw method checks the balance, awaits, and then subtracts:
var account = new Account(100);
var tasks = Enumerable.Range(0, 5).Select(_ => account.WithdrawAsync(80));
bool[] results = await Task.WhenAll(tasks);
Console.WriteLine($"succeeded: {results.Count(ok => ok)}, balance: {account.Balance}");
var safe = new SafeAccount(100);
results = await Task.WhenAll(Enumerable.Range(0, 5).Select(_ => safe.WithdrawAsync(80)));
Console.WriteLine($"succeeded: {results.Count(ok => ok)}, balance: {safe.Balance}");
class Account(decimal balance)
{
public decimal Balance => balance;
public async Task<bool> WithdrawAsync(decimal amount)
{
if (balance < amount) return false; // check
await Task.Delay(10); // e.g. call a fraud-check service
balance -= amount; // act, on stale information
return true;
}
}
class SafeAccount(decimal balance)
{
private readonly SemaphoreSlim _mutex = new(1, 1);
public decimal Balance => balance;
public async Task<bool> WithdrawAsync(decimal amount)
{
await _mutex.WaitAsync();
try
{
if (balance < amount) return false;
await Task.Delay(10);
balance -= amount;
return true;
}
finally
{
_mutex.Release();
}
}
}
succeeded: 5, balance: -140
succeeded: 1, balance: 20
All five withdrawals pass the check before any of them subtracts. The balance isn't even the "expected wrong" value of 100 - 5 * 80 = -300: the continuations ran in parallel on the thread pool, and balance -= amount lost updates too. Two races in six lines.
You can't fix this with lock. The compiler doesn't allow it, because the code after await may resume on a different thread than the one that took the lock:
lock (gate)
{
await Task.Delay(1);
n++;
}
error CS1996: Cannot await in the body of a lock statement
SemaphoreSlim(1, 1) with await WaitAsync() is the async-compatible mutex. Always release it in finally.
Visibility: a flag that is never seen
This worker spins until another thread sets _stop:
var worker = new Worker();
var thread = new Thread(worker.Run) { IsBackground = true };
thread.Start();
Thread.Sleep(500);
worker.Stop();
Console.WriteLine("Stop() called");
bool finished = thread.Join(TimeSpan.FromSeconds(2));
Console.WriteLine(finished ? "worker stopped" : "worker is still spinning after 2 seconds");
class Worker
{
private bool _stop;
public long Iterations;
public void Run()
{
long n = 0;
while (!_stop)
n++;
Iterations = n;
}
public void Stop() => _stop = true;
}
With dotnet run -c Release:
Stop() called
worker is still spinning after 2 seconds
With the default Debug build, it prints worker stopped. In Release, the JIT sees that nothing in the loop writes _stop, so it reads the field once and loops forever on that cached value. That's a legal optimization for single-threaded code.
Declaring the field volatile (private volatile bool _stop;) makes every read go to memory, and the program prints worker stopped. Volatile.Read(ref _stop) and Volatile.Write(ref _stop, true) do the same thing for a single access. See volatile.
In real code, use a CancellationToken instead of a hand-rolled flag. It's already thread-safe and it works with await, Task.Delay and most I/O APIs.
volatile only fixes visibility. A volatile int still loses updates with ++.
Torn reads of large structs
A reference, an int or (on 64-bit) a long is read and written atomically. A bigger struct is copied in several pieces. A reader can see a value that was never written:
var holder = new Holder();
var writer = new Thread(() =>
{
for (long i = 0; ; i++)
holder.Range = i % 2 == 0 ? new Range2(0, 0) : new Range2(1_000, 1_000);
}) { IsBackground = true };
writer.Start();
int torn = 0;
for (int i = 0; i < 10_000_000; i++)
{
Range2 r = holder.Range; // 16-byte copy, not atomic
if (r.Start != r.End && torn++ < 3)
Console.WriteLine($"torn read: Start={r.Start}, End={r.End}");
}
Console.WriteLine($"torn reads: {torn:N0} of 10,000,000");
record struct Range2(long Start, long End);
class Holder { public Range2 Range; }
torn read: Start=0, End=1000
torn read: Start=1000, End=0
torn read: Start=1000, End=0
torn reads: 5,437,183 of 10,000,000
The writer only ever stores (0, 0) and (1000, 1000), yet the reader sees (0, 1000) millions of times. decimal, Guid, DateTimeOffset and your own multi-field structs all have this problem.
Change Range2 to an immutable class (record Range2(long Start, long End);), initialize the field (public Range2 Range = new(0, 0);) so the reader never sees null, and the same program prints torn reads: 0 of 10,000,000. Now the field holds a reference, which is replaced atomically, and each object never changes after it's created. This is the immutable snapshot pattern: build a new object off to the side, then publish it with one reference assignment (or Interlocked.Exchange / CompareExchange if several writers race). Readers need no lock. Immutable collections and FrozenDictionary work well for configuration or lookup tables that are replaced as a whole.
The best fix: don't share
Every fix above coordinates access to shared mutable state. Often you can avoid sharing altogether: give each thread its own data and combine the results at the end.
long total = 0;
Parallel.For(1, 1_000_001,
localInit: () => 0L,
body: (i, _, subtotal) => subtotal + i, // no sharing here
localFinally: subtotal => Interlocked.Add(ref total, subtotal));
Console.WriteLine($"Parallel.For: {total:N0}");
long sum = Enumerable.Range(1, 1_000_000).AsParallel().Sum(i => (long)i);
Console.WriteLine($"PLINQ Sum: {sum:N0}");
Parallel.For: 500,000,500,000
PLINQ Sum: 500,000,500,000
The Parallel.For overload with localInit/localFinally gives each worker its own subtotal, so only one Interlocked.Add per worker touches shared state, instead of one per item. Compare it with the lock-per-iteration version in Controlling access to a variable in a Parallel.For loop. PLINQ aggregates, Task.WhenAll returning results, and Channel<T> (a single consumer owns the state, producers send it messages) follow the same idea.
Choosing a fix
| Situation | Use |
|---|---|
| Counter, sum, flag, one-time guard | Interlocked |
| Several fields that must change together | lock on a private Lock |
Critical section that contains await |
SemaphoreSlim(1, 1) + WaitAsync |
| Shared dictionary / queue | ConcurrentDictionary, ConcurrentQueue, with compound methods |
| Expensive value computed once | Lazy<T>, or ConcurrentDictionary<K, Lazy<V>> |
| Stop signal | CancellationToken (or volatile bool) |
| Data that is read often and replaced rarely | immutable object, swapped atomically |
| Parallel computation | per-thread state + combine (localInit, PLINQ, Task.WhenAll) |
Finding races
.NET has no built-in race detector like Go's -race or C++'s ThreadSanitizer, so finding races takes discipline:
- Review shared state. For every field that more than one thread touches, write down what protects it. Static fields, singletons and services registered as singletons in ASP.NET Core (shared by all requests) are the usual suspects.
- Stress test in Release. Run the suspicious code many times on many threads, in a loop, with optimizations on. Races that never show up in a Debug build appear in Release, as the visibility example shows.
- Widen the window. Temporarily put
Thread.Sleep(1)orawait Task.Yield()between the check and the act. If the code breaks, you found a race. - Read exceptions as hints.
InvalidOperationException: Operations that change non-concurrent collections must have exclusive access,IndexOutOfRangeExceptioninsideList<T>orDictionarycode, andNullReferenceExceptionin code that "can't" see null often mean concurrent access. - Check documentation. Most .NET types are documented as "Any public static members of this type are thread safe. Any instance members are not guaranteed to be thread safe."
HttpClientis safe to share, whileDbContext,List<T>,Dictionary<K,V>,StringBuilderandRandominstances are not (Random.Sharedis).