Locks: The Single Key

Locks: The Single Key in C#: A restaurant with several cooks keeps its expensive ingredients in a small storeroom, and the storeroom has exactly one key,…

The Analogy: One Key on the Hook

A restaurant with several cooks keeps its expensive ingredients in a small storeroom, and the storeroom has exactly one key, hanging on a hook by the door. To take stock you fetch the key, unlock the room, do your business, come back and hang the key up again. If someone else already has the key, you wait by the hook. It is not fast, and it is not clever, but it is correct: two people can never be rearranging the shelves at the same time.

That is a lock. The key does not protect the room — the room is the shared data, and nothing physically stops a determined cook from climbing in the window. The key protects the agreement: everyone who touches the shelves promises to hold the key first. A lock in C# is exactly this kind of promise, enforced only by the code that honours it. One thread forgetting to take the key ruins the protection for everyone, and the compiler will not warn you.

The critical insight is what happens between "read the shelf" and "write the shelf". Two cooks both read "3 onions", both take one, both write back "2 onions" — and one onion has vanished from the books. count++ is exactly this: a read, an add, and a write, with room for another thread to slip in between. The operation looks atomic in the source because it is one short line, and it is three instructions in the machine.

Which brings us to the cost of keys. Every trip to the hook is time not spent cooking, and if the storeroom is the busiest room in the kitchen, your two extra cooks queue at a door instead of working. Good synchronisation is not about locking more; it is about arranging the work so there is less to lock — and knowing which of the cheaper alternatives to reach for when a full key is more than you need.


Syntax or Core Structure

using System;
using System.Threading;

class Counter
{
    private readonly object gate = new object();   // private, dedicated, readonly
    private int count;

    public void Increment()
    {
        lock (gate)          // only one thread may be inside this block
        {
            count++;         // read, add, write - three steps, one key
        }
    }

    public int Count
    {
        get { lock (gate) { return count; } }      // reads need the key too
    }
}

class Program
{
    static void Main()
    {
        Counter safe = new Counter();
        int fast = 0;

        Thread[] threads = new Thread[4];
        for (int t = 0; t < threads.Length; t++)
        {
            threads[t] = new Thread(() =>
            {
                for (int i = 0; i < 25_000; i++)
                {
                    safe.Increment();
                    Interlocked.Increment(ref fast);   // lock-free equivalent
                }
            });
            threads[t].Start();
        }
        foreach (Thread t in threads) t.Join();

        Console.WriteLine("expected     = " + 4 * 25_000);
        Console.WriteLine("locked       = " + safe.Count);
        Console.WriteLine("interlocked  = " + fast);
    }
}

Output:

expected     = 100000
locked       = 100000
interlocked  = 100000

Both counters land on exactly 100,000, every run, on every machine. Delete the lock and count++ alone will usually come out short — a few dozen to a few thousand increments lost — and the shortfall changes every time you run it, which is the signature of a data race and the reason races survive so long in production code.

Three details in Counter are deliberate. The gate is private, so no outside code can lock the same object and interfere with your critical section. It is readonly, because reassigning it mid-flight would leave two threads locking two different objects and believing they were synchronised. And the Count getter locks as well: a read of a shared int may be atomic on its own, but without the lock the reader has no guarantee of seeing the most recent write.

Interlocked.Increment reaches the same answer without a lock at all, using a single CPU instruction that reads, adds and writes as one indivisible step. It is dramatically cheaper than a lock — but it only covers one variable at a time, which is why it can replace a counter and cannot replace a bank transfer.


Technical Depth: Choosing the Right Primitive

lock is syntax sugar. The compiler turns it into Monitor calls wrapped in try/finally, which is what guarantees the key goes back on the hook even if the body throws:

lock (gate) { count++; }

// roughly compiles to:
bool taken = false;
try { Monitor.Enter(gate, ref taken); count++; }
finally { if (taken) Monitor.Exit(gate); }

Since .NET 9 there is also a dedicated System.Threading.Lock type; lock recognises it and uses a faster path, so private readonly Lock gate = new(); is the modern default for new code.

PrimitiveUse it forNotes
lock / MonitorProtecting a few statements over shared stateReentrant on the same thread; cannot be used with await
InterlockedCounters, flags, single-variable swapsLock-free, one variable only
SemaphoreSlimLimiting concurrency to N; async critical sectionsThe only one with WaitAsync
ReaderWriterLockSlimMany readers, rare writersOnly pays off when reads greatly outnumber writes
ManualResetEventSlim"Wait until something has happened"Signalling, not mutual exclusion
MutexExclusion across processesNamed, OS-level, far slower
Concurrent* collectionsShared queues, maps, bagsAlready synchronised; do not add your own lock

What you must never lock on

lock (this)             // callers can lock your instance too
lock (typeof(Order))    // shared with every assembly in the process
lock ("gate")           // string literals are interned - globally shared!
lock (someList)         // anyone else holding a reference can lock it

Each of these hands the key to code you have never seen. A private, dedicated gate object costs one field and removes the entire class of problem.

Deadlock, and the one rule that prevents it

A deadlock needs only two locks and two threads going in opposite directions: thread A holds x and wants y, thread B holds y and wants x, and neither will ever let go. No exception is thrown and no timeout fires — the threads simply stop, forever, which is why deadlocks are usually diagnosed from a dump rather than a log.

The rule that prevents it is consistent ordering: if every thread that needs two locks always takes them in the same global order, a cycle cannot form. Any total order will do as long as everyone agrees — an id, a name, a fixed hierarchy. Monitor.TryEnter(gate, timeout) is the fallback when ordering is genuinely impossible, letting you give up and retry instead of hanging.

Async and locks do not mix

await inside a lock body is a compile error, and for good reason: Monitor is tied to the thread that entered it, and a continuation may resume on a different one. For an async critical section use SemaphoreSlim(1, 1):

private readonly SemaphoreSlim gate = new SemaphoreSlim(1, 1);

await gate.WaitAsync(token);
try { await SaveAsync(); }
finally { gate.Release(); }        // the finally is not optional

Volatile, and why you rarely need it

volatile prevents the compiler and CPU from caching or reordering reads and writes of a single field — enough for a "please stop" flag, and not enough for anything with more than one variable in it. Volatile.Read/Volatile.Write express the same thing per-operation and are easier to reason about. If you are reaching for either to make a multi-field invariant safe, you need a lock instead.

Granularity is a design decision

One lock around an entire service is trivially correct and serialises everything. One lock per key (or a ConcurrentDictionary) allows real concurrency and multiplies the chances of a deadlock. Start coarse, measure contention, and split only where the profiler says the queue at the door is the problem.


Real World Example: Transferring Between Accounts

A transfer touches two accounts and must be all-or-nothing: money may never appear, disappear, or go negative, no matter how many threads are moving it at once. This is the canonical two-lock problem, and the canonical deadlock.

using System;
using System.Threading;

class Account
{
    public Account(int id, decimal opening) { Id = id; balance = opening; }

    public int Id { get; }
    internal readonly object gate = new object();
    private decimal balance;

    public decimal Balance { get { lock (gate) { return balance; } } }

    internal bool CanTake(decimal amount) => balance >= amount;  // caller holds the key
    internal void Add(decimal amount) => balance += amount;      // caller holds the key
}

class Bank
{
    private int completed;
    private int rejected;

    public int Completed => Volatile.Read(ref completed);
    public int Rejected => Volatile.Read(ref rejected);

    public void Transfer(Account from, Account to, decimal amount)
    {
        // Always take the lower id first. Two threads moving money in
        // opposite directions can then never hold each other's key.
        Account first = from.Id < to.Id ? from : to;
        Account second = from.Id < to.Id ? to : from;

        lock (first.gate)
        {
            lock (second.gate)
            {
                if (!from.CanTake(amount))
                {
                    Interlocked.Increment(ref rejected);
                    return;
                }

                from.Add(-amount);
                to.Add(amount);
                Interlocked.Increment(ref completed);
            }
        }
    }
}

class Program
{
    static void Main()
    {
        Account a = new Account(1, 1000m);
        Account b = new Account(2, 1000m);
        Bank bank = new Bank();

        Console.WriteLine("opening total: " + (a.Balance + b.Balance));

        Thread[] threads = new Thread[4];
        for (int t = 0; t < threads.Length; t++)
        {
            bool aToB = t < 2;                    // fresh local, safe to capture
            threads[t] = new Thread(() =>
            {
                for (int i = 0; i < 500; i++)
                {
                    if (aToB) bank.Transfer(a, b, 1m);
                    else      bank.Transfer(b, a, 1m);
                }
            });
            threads[t].Start();
        }
        foreach (Thread t in threads) t.Join();

        Console.WriteLine("completed: " + bank.Completed + ", rejected: " + bank.Rejected);
        Console.WriteLine("A = " + a.Balance + ", B = " + b.Balance);
        Console.WriteLine("closing total: " + (a.Balance + b.Balance));
    }
}

Output:

opening total: 2000
completed: 2000, rejected: 0
A = 1000, B = 1000
closing total: 2000

The numbers are deterministic for two different reasons, and it is worth separating them. The closing total is 2000 because the invariant holds: inside the lock, one debit and one credit of equal size happen together, so no interleaving can ever create or destroy money. The final balances are 1000 each because the workload is symmetric — two threads push 500 each way — and no transfer is ever rejected, because A can lose at most the 1000 it started with.

The ordering trick is the whole lesson. Written naively as lock (from.gate) { lock (to.gate) { ... } }, this program deadlocks: an A→B thread holds A and waits for B while a B→A thread holds B and waits for A. Sorting the two accounts by Id before locking means every thread in the process takes account 1 before account 2, a cycle becomes impossible, and the naive version's intermittent hang disappears. The comparison key does not matter as long as it is total and everyone uses it.

CanTake and Add are deliberately internal and deliberately unlocked, with the contract written in a comment: the caller holds the key. This is the honest way to build a compound operation — the alternative, where each small method locks for itself, would make the check-then-act pair look safe while leaving a gap between the check and the debit that another thread can walk straight through. The counters use Interlocked rather than the accounts' locks because they are independent of any account, and Volatile.Read on the way out ensures the reporting thread sees the final values.


Common Mistakes

  1. Locking around each step instead of the whole operation. Two individually-locked methods do not make a locked pair; the invariant must be inside a single critical section.
  2. Locking on this, a type, a string literal, or a public field. All of them are reachable from outside your class, so someone else's lock can block yours or vice versa. Use a private readonly gate.
  3. Taking two locks in whatever order the arguments arrive. This is the standard deadlock, and it will pass every test on a quiet machine before hanging in production. Sort by a stable key.
  4. Reading shared state without the lock. A read that skips the key can see a value from before another thread's write, or a half-updated pair of fields.
  5. Reassigning a non-readonly gate. Two threads then lock two different objects and both believe they are alone.
  6. Calling out to unknown code while holding a lock. Raising an event, invoking a callback, or awaiting I/O inside a critical section invites both deadlock and unbounded hold times. Compute inside, call outside.
  7. Using volatile where a lock is needed. It orders one field's access; it cannot make a two-field invariant atomic.
  8. Adding your own lock around a ConcurrentDictionary. It is already thread-safe, and the extra key destroys the concurrency you paid for. Use GetOrAdd or AddOrUpdate instead of read-then-write.

Best Practices

  • Give every lockable resource a private readonly gate object, and on .NET 9 or later prefer the dedicated Lock type.
  • Keep critical sections short and free of I/O, callbacks, and events — do the slow work outside the key.
  • Use Interlocked for single-variable counters and flags, and a lock only when an invariant spans more than one variable.
  • When two locks are unavoidable, define one global ordering (an id, a name) and take them in that order everywhere.
  • Use SemaphoreSlim(1, 1) with WaitAsync for async critical sections, and always Release in a finally.
  • Document which lock protects which fields, in a comment beside the gate — future readers cannot infer it.
  • Prefer designs that need no lock at all: immutable objects, thread-local accumulation, message passing through a Channel, or a Concurrent* collection.
  • Test concurrency with far more iterations and threads than production will use; races hide at low volume.

Practice Exercises

  1. Remove the lock from Counter.Increment and run the program ten times, recording each result. Then restore it. Explain why the losses vary and why they are always losses, never gains.
  2. Rewrite Transfer to lock from then to with no ordering, and run the four-thread workload in a loop until it hangs. Capture the thread states and identify which thread holds which key.
  3. Build a thread-safe Cache<TKey, TValue> with GetOrCreate(key, factory). Guarantee the factory runs at most once per key even under concurrent calls, then compare your implementation with ConcurrentDictionary.GetOrAdd and note the difference in factory guarantees.
  4. Convert the Bank to an async API using SemaphoreSlim per account, keeping the id-ordering rule. Show that await inside lock does not compile, and explain what the semaphore changes about which thread owns the critical section.