Skip to content
Tutorials Center
My learning

Topics

Lesson 101 of 182 ยท Async and Concurrency

lock, Lock and Interlocked

Make shared data thread-safe in C# - the lock statement, System.Threading.Lock, Monitor, Interlocked, Volatile, deadlocks and how to avoid them, SemaphoreSlim and ReaderWriterLockSlim.

When two threads change the same variable at the same time, the result is a race condition: the answer depends on who wins, and often it is simply wrong. Fixing that is called synchronization. .NET gives you a small toolbox: lock for "only one thread in this section at a time", Interlocked for single atomic operations, SemaphoreSlim to limit how many callers get in, and ReaderWriterLockSlim for data that is read far more often than written.

This lesson builds on Threads and Tasks. You will see a race fixed three different ways, the new System.Threading.Lock type from .NET 9, a deadlock (and how to make one impossible), and how to throttle async work. As always, the examples here use Join and other signals so their output is the same on every run.

Why a plain count++ is not safe

count++ looks like one step but is three: read the value, add one, write it back. If two threads read the same old value, both write old + 1, and one increment is lost. The more threads and iterations, the more updates vanish.

C#
// BROKEN: shown read-only on purpose, the result changes from run to run
int count = 0;
var threads = Enumerable.Range(0, 4).Select(_ => new Thread(() =>
{
    for (int i = 0; i < 100_000; i++) { count++; }   // lost updates
})).ToList();
threads.ForEach(t => t.Start());
threads.ForEach(t => t.Join());
Console.WriteLine(count);   // often less than 400000

On a quiet one-core sandbox this may even print 400000 by luck, which is exactly the danger: the bug hides during testing and shows up under production load. We do not run it as a live example because its output would not be stable.

The lock statement

lock (obj) { ... } lets one thread at a time into the block. Others wait at the door. When the owner leaves the block (normally or by exception), the lock is released and one waiting thread enters.

C# lock makes the counter exact

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.

Every access to count must use the same lock object, otherwise there is no protection. The rules for a good lock object:

  • Use a private, dedicated object (private readonly object _gate = new();). Never lock (this), lock (typeof(X)) or lock ("text"): other code can lock the same object and cause surprise deadlocks.
  • Keep the locked section short. Do not call unknown code (callbacks, events, I/O) while holding a lock.
  • Lock around a whole invariant. If two fields must change together, update both inside one lock, and read both inside the same lock too.

System.Threading.Lock (.NET 9, C# 13)

.NET 9 added a dedicated System.Threading.Lock type. It is used with the same lock statement, but the compiler recognizes it and generates faster code than Monitor on a plain object. It also states your intent: this field is a lock and nothing else. For new code, prefer it.

C# Using the Lock type

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.

Note the getter also takes the lock: a reader must see a consistent value. Lock also has EnterScope(), which returns a Lock.Scope struct you can use with using. That is the same as lock but lets you enter and exit in different code shapes:

C#
using (_gate.EnterScope())
{
    _balance += amount;
}

If you assign a Lock to a variable of type object and lock on that, the compiler falls back to ordinary Monitor behavior and you lose the benefit (the compiler warns about it). Keep the field typed as Lock.

You cannot await inside a lock

A lock is owned by a thread, but an await may resume on a different thread, so C# forbids await inside lock. The compiler rejects it:

C# await inside lock (fails on purpose)

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.

The error is error CS1996: Cannot await in the body of a lock statement. For async code use SemaphoreSlim, shown below, which can be awaited.

Interlocked: atomic single operations

For one simple operation on one variable, a lock is overkill. The Interlocked class performs read-modify-write as one indivisible CPU operation: no lock, no waiting. It works on int, long, and other primitives through ref.

C# Interlocked.Increment and Add

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.

Each call is atomic on its own. Two separate Interlocked calls are not atomic together, so do not use them to keep two variables consistent: use a lock for that.

CompareExchange: the building block of lock-free code

Interlocked.CompareExchange(ref location, newValue, comparand) says: "if the variable still equals comparand, set it to newValue; either way tell me the value that was there." You put it in a loop to build any update: read the current value, compute the new one, try to swap; if somebody changed the value in between, try again.

C# A lock-free maximum with CompareExchange

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.

Interlocked.Exchange sets a value and returns the old one in a single step, handy for "take the pending item and leave null behind". Use Interlocked for counters, flags and simple swaps; reach for lock the moment the logic involves more than one variable.

Volatile and visibility

Synchronization is also about visibility. The compiler and CPU may cache a variable in a register or reorder reads and writes, so one thread might never see another thread's change. Volatile.Read and Volatile.Write (or a volatile field) guarantee you read the latest value and that writes before it are visible. lock and Interlocked already include these guarantees. You need Volatile mostly for a simple stop flag:

C# A stop flag with Volatile

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.

Without Volatile, an optimizing JIT is allowed to read stopRequested once and loop forever. For anything more complicated than a flag, use a lock or a CancellationToken (see Cancellation and Timeouts).

Monitor: what lock really does

lock (x) { body } is shorthand for Monitor.Enter / Monitor.Exit inside a try/finally. You use Monitor directly when you need more control: TryEnter with a timeout, or Wait and Pulse for signalling between threads.

C# Monitor.TryEnter with a timeout

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.

TryEnter gives you a way to give up instead of waiting forever, which is a useful safety net. Remember: every successful Enter or TryEnter needs a matching Exit, preferably in a finally.

Deadlock

A deadlock happens when threads wait for each other forever. The classic recipe is two locks taken in opposite orders: thread A holds lock 1 and wants lock 2, thread B holds lock 2 and wants lock 1. Neither can move.

The example below creates exactly that situation, but uses TryEnter with a timeout so the program reports the problem instead of freezing. A barrier makes both threads hold their first lock before they reach for the second, so the outcome is reliable.

C# A deadlock caught by timeouts

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.

With plain lock for the second step, both threads would wait forever and the program would hang (the sandbox would stop it after its time limit).

How to avoid deadlocks:

  1. Always take multiple locks in the same global order. Give locks a rank (for example by account id) and lock the lower one first.
  2. Hold as few locks as possible, for as short as possible. Prefer one lock for the whole data structure.
  3. Never call foreign code while holding a lock (events, virtual methods, callbacks): you do not know what locks it takes.
  4. Use TryEnter with a timeout and log a failure when you cannot avoid nesting.
C# Fix: lock in a consistent order

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.

Both threads move money in opposite directions, but because both lock account 1 before account 2, a cycle of waiting can never form. The money is conserved: the total is always 200.

SemaphoreSlim: letting N threads in

A lock admits one thread. A semaphore admits up to N. SemaphoreSlim is initialized with a count; Wait takes a permit (blocking if none are left), Release gives one back. Unlike lock, it has WaitAsync, so it works with await, and it is the standard tool for limiting concurrency in async code.

C# Limit concurrency to 2 with SemaphoreSlim

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.

Always release in a finally, or one exception will leak a permit and eventually starve everyone. A SemaphoreSlim(1, 1) is an async-friendly mutex: use it when you need mutual exclusion around code that awaits.

ReaderWriterLockSlim: many readers, one writer

If data is read constantly but changed rarely (a configuration table, a lookup cache), a plain lock makes readers wait for each other for no reason. ReaderWriterLockSlim allows any number of simultaneous readers, but a writer needs exclusive access.

C# Readers share, writers are exclusive

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.

ReaderWriterLockSlim is heavier than lock, so it only pays off when reads dominate and the work inside the read lock is not trivial. For most cases a simple Lock or a concurrent collection (see Concurrent Collections) is both simpler and as fast. Reader-writer locks also have rules that bite: recursion is disabled by default and upgrading a read lock to a write lock needs EnterUpgradeableReadLock.

Choosing a tool

Situation Use
One counter or flag Interlocked (or Volatile for a plain flag)
Several fields that change together lock with a private Lock
Need a timeout or signalling Monitor.TryEnter, Wait/Pulse, or events like ManualResetEventSlim
Limit parallel callers, or lock around await SemaphoreSlim
Read-mostly shared data ReaderWriterLockSlim, or an immutable snapshot swapped with Interlocked.Exchange
A shared dictionary, queue or bag A concurrent collection

The best synchronization is none: share less. Give each thread its own data, pass results back through channels, or use immutable objects that can be shared freely.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why can count++ lose updates when run on several threads?

    Two threads can read the same old value and both write old + 1, so one increment is lost.
  2. 2. Which object is a good target for the lock statement?

    Other code can reach this, type objects and interned strings, which invites accidental deadlocks. A private dedicated object cannot be locked by outsiders.
  3. 3. Why does the compiler reject await inside a lock block?

    Ownership by thread breaks across an await. Use SemaphoreSlim and WaitAsync for async mutual exclusion.
  4. 4. Two threads each lock A then B, but one locks in the order B then A. What can happen?

    Opposite lock orders can create a cycle of waiting. Always acquire multiple locks in one global order.
  5. 5. Which type limits an async operation to at most 5 concurrent callers?

    SemaphoreSlim with a count of 5 admits five callers at once, and WaitAsync lets them wait without blocking threads.

Summary

  • Shared mutable data needs protection: count++ is read, add, write and loses updates under concurrency.
  • lock (ideally on a private System.Threading.Lock) lets one thread at a time into a section; keep it short and never await inside it.
  • Interlocked makes single operations atomic and CompareExchange builds lock-free updates; Volatile guarantees visibility for simple flags.
  • Monitor offers TryEnter with timeouts; deadlocks come from inconsistent lock order, so lock in one global order.
  • SemaphoreSlim limits concurrency and works with await; ReaderWriterLockSlim helps read-mostly data.
  • Prefer sharing less: thread-local data, immutability, channels and concurrent collections.

Next: Concurrent Collections