Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Async and Concurrency

The Interlocked class

Reference for System.Threading.Interlocked in C#: atomic increment, add, exchange and compare-and-swap, with lock-free patterns and their limits.

Interlocked provides atomic operations on shared variables. counter++ looks like one step, but it is a read, an add and a write; two threads can interleave and lose an update. Interlocked.Increment(ref counter) does the whole thing as one indivisible step using a CPU instruction, without taking a lock.

Use it for counters, flags and simple lock-free algorithms built on compare-and-swap: "set this variable to a new value only if it still has the value I last saw".

C#
int hits = 0;
Interlocked.Increment(ref hits);

Try it

C# Lost updates versus atomic updates

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# Compare-and-swap loops

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.

Syntax

C#
public static class Interlocked
{
    public static int Increment(ref int location);
    public static long Decrement(ref long location);
    public static int Add(ref int location1, int value);
    public static int Exchange(ref int location1, int value);
    public static T Exchange<T>(ref T location1, T value) where T : class?;
    public static int CompareExchange(ref int location1, int value, int comparand);
    public static T CompareExchange<T>(ref T location1, T value, T comparand) where T : class?;
    public static int And(ref int location1, int value);
    public static int Or(ref int location1, int value);
    public static long Read(ref long location);
    public static void MemoryBarrier();
}
Name Description
location1 The variable to change. It must be a field, array element or local passed by ref; not a property.
value The operand or the new value.
comparand The value location1 must currently have for CompareExchange to store value.

Returns: Increment, Decrement and Add return the new value. Exchange, CompareExchange, And and Or return the original value. Overloads exist for int, long, uint, ulong, float, double, object/T, nint and nuint (not every operation for every type).

Errors: NullReferenceException if the ref points to a null location (rare). The operations themselves cannot fail.

Usage notes

  • Every access must be atomic. If one thread uses Interlocked.Increment(ref n) and another writes n = 0 plainly, the guarantees are weaker. Read with Volatile.Read or Interlocked.Read, write with Interlocked.Exchange or Volatile.Write.
  • Full fences. Interlocked operations are full memory barriers: reads and writes before them cannot move after, and vice versa.
  • Retry loops must recompute. In a compare-and-swap loop, re-read the variable and recalculate the new value on each failure.
  • The ABA problem. A value can change from A to B and back to A between your read and your swap, so a matching comparand does not prove nothing happened. For reference-based structures use immutable nodes or version counters.
  • Only for one variable. Two related variables cannot be updated atomically with Interlocked; use a lock or combine them into one immutable object swapped by reference.
  • Contention. Many threads hammering one counter slow each other because the cache line bounces between cores. For hot counters, use per-thread counters and add them up at the end.
  • On 32-bit processes plain reads of long can tear; Interlocked.Read is the safe way.
  • Interlocked.And/Or were added in .NET 5; bool and enum fields cannot be passed directly, so use an int flag word.