Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Async and Concurrency

Race conditions

What a race condition is in C#, why counter++ loses updates, how check-then-act fails, and how lock, Interlocked and immutability remove the bug.

A race condition is a bug whose outcome depends on the timing of operations in different threads. The program is correct when the operations happen to interleave one way and wrong when they interleave another way. Because the timing changes from run to run, the bug appears only sometimes, disappears under a debugger and often passes all tests.

The classic case is a read-modify-write on shared data. count++ looks like one step but is three: read the value, add one, write it back. If two threads both read 5, both write 6, one increment is lost.

C#
count++;                       // not atomic: read, add, write
Interlocked.Increment(ref count);   // atomic

Try it

C# A lost update, made certain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Fixing it with lock and Interlocked

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Common shapes

Read-modify-write

x++, x += n, list.Count + 1 stored back, and total = total + price are all unsafe on shared variables. Fix with lock, Interlocked (for numbers), or by not sharing the variable (each thread keeps a local total and you combine them at the end).

Check-then-act

C#
// Read-only: two threads can both pass the check
if (!cache.ContainsKey(key))
{
    cache[key] = Load(key);
}

Between the check and the action another thread may change the state. Make the pair atomic with one lock, or use an operation designed for it, such as ConcurrentDictionary.GetOrAdd or TryAdd. Note that GetOrAdd may run the value factory more than once under contention (only one result is stored); wrap values in Lazy<T> when the factory must run once.

Unsafe publication and visibility

Without synchronization, one thread's write may not be visible to another in a predictable order. Use volatile, Volatile.Read/Write, locks or Interlocked when sharing flags and references.

Non-thread-safe collections

List<T>, Dictionary<TKey,TValue> and most of System.Collections.Generic are not safe for concurrent writes. Concurrent use can lose items, throw odd exceptions or corrupt the structure. Use the types in System.Collections.Concurrent, or lock around every access.

Usage notes

  • Races are not always on memory. Two processes creating the same file, or two requests updating the same database row, are races too. Use unique constraints, transactions or optimistic concurrency checks there.
  • Async code races as well. Two awaited operations running on different thread-pool threads can modify the same field. Being "async" does not make shared state safe.
  • Prefer to share less. Immutable objects, message passing (Channel<T>), per-thread state and Parallel.For with thread-local accumulators avoid the problem instead of guarding against it.
  • Do not trust a passing test. A race that fails one run in a thousand is still a bug. To expose one, force the interleaving (as in the first example) or stress the code with many iterations and threads.
  • Tools: thread-safety analyzers, code review of every shared mutable field, and stress tests. The runtime has no built-in race detector.
  • Lock the same object everywhere. A lock only works if all code paths touching the data use the same lock object. Use a private object (or System.Threading.Lock in .NET 9+), never this or a string.
  • Atomic is not the same as consistent. Two separate Interlocked operations on two variables are each atomic, but a reader may see one updated and the other not; guard related fields with one lock.