Select Page

Two threads can stop each other when one holds the left lock and needs the right, while the other holds the right and needs the left. Fix this acquisition cycle by making every operation take the locks in one consistent order, even when the operation moves data in the opposite direction.

This tutorial recreates the conflicting ownership with timed monitor attempts, then checks the ordered fix with repeated transfers and cancellation. The experiment ends on its own; it does not leave permanently blocked foreground threads.

Verified 31 October 2026 with .NET SDK 10.0.402, runtime 10.0.13, Linux x64. Both complete console programs target .NET 10 with its default C# 14 language version. No external packages or preview features are required. Microsoft documents the framework-to-language defaults.

Identify the two-lock dependency

Ownership when acquisition orders disagree
Worker Already owns Needs next
A left right, owned by B
B right left, owned by A

With unbounded second acquisitions, each worker waits for the other to release its first lock. Neither reaches the release. Microsoft’s managed threading guidance describes this deadlock pattern. Here, finite waits let us observe the conflicting ownership and recover.

This is a different dependency from blocking on an asynchronous operation whose continuation needs the blocked thread. For that case, see our existing tutorial on diagnosing an async deadlock.

Reproduce the conflict with bounded waits

Create a .NET 10 console project with dotnet new console --framework net10.0. Replace Program.cs with this complete program and run dotnet run. Run each program below separately.

using System;
using System.Threading;

object left = new();
object right = new();
using var firstHeld = new CountdownEvent(2);
using var attemptsFinished = new CountdownEvent(2);
bool[] timedOut = new bool[2];
Exception?[] errors = new Exception?[2];

void Worker(int index, object first, object second)
{
    bool firstTaken = false;
    bool secondTaken = false;
    try
    {
        Monitor.TryEnter(first, 1000, ref firstTaken);
        if (!firstTaken) throw new TimeoutException("First lock unavailable.");
        firstHeld.Signal();
        if (!firstHeld.Wait(5000))
            throw new TimeoutException("Workers did not rendezvous.");

        Monitor.TryEnter(second, 200, ref secondTaken);
        timedOut[index] = !secondTaken;
        attemptsFinished.Signal();
        // Keep the first lock until BOTH second-lock attempts have finished.
        if (!attemptsFinished.Wait(5000))
            throw new TimeoutException("Second attempt did not finish.");
    }
    catch (Exception error)
    {
        errors[index] = error;
    }
    finally
    {
        if (secondTaken) Monitor.Exit(second);
        if (firstTaken) Monitor.Exit(first);
    }
}

var a = new Thread(() => Worker(0, left, right)) { IsBackground = true };
var b = new Thread(() => Worker(1, right, left)) { IsBackground = true };
a.Start();
b.Start();
bool joinedA = a.Join(10000);
bool joinedB = b.Join(10000);
if (!joinedA || !joinedB) throw new TimeoutException("Worker did not stop.");
foreach (Exception? error in errors)
    if (error is not null) throw new Exception("Worker failed.", error);
if (!timedOut[0] || !timedOut[1])
    throw new Exception("Expected both second-lock attempts to time out.");

foreach (object gate in new[] { left, right })
{
    bool taken = false;
    try
    {
        Monitor.TryEnter(gate, 1000, ref taken);
        if (!taken) throw new Exception("A lock leaked.");
    }
    finally
    {
        if (taken) Monitor.Exit(gate);
    }
}
Console.WriteLine("Second-lock timeouts: 2");
Console.WriteLine("Workers joined; both locks released");
Second-lock timeouts: 2
Workers joined; both locks released

The first countdown ensures both workers own their first, different lock before either attempts its second. The second countdown keeps those first locks held until both second-lock attempts have finished. Without that second rendezvous, one worker could time out, release its first lock, and allow the other worker to succeed. CountdownEvent.Wait supports the finite rendezvous waits used here.

The 200-millisecond attempts must both fail because their requested locks remain owned by the other worker. This demonstrates the ownership cycle that would deadlock with indefinite acquisitions; the timed program itself recovers. A timeout in arbitrary production code alone does not prove deadlock: a slow owner or scheduling delay can also cause one.

The Monitor.TryEnter contract distinguishes acquiring the lock from timing out. Each ownership flag starts false, and finally releases only locks actually acquired. After joining the workers, the main thread reacquires both monitors to check cleanup. The timed Thread.Join overload reports whether a worker terminated; it does not cancel that worker. Background threads provide a last-resort process-exit safeguard if an assertion fails, while the successful path explicitly joins every worker before disposing synchronization objects.

Keep the lock order independent of transfer direction

For this two-resource example, the rule is simply: acquire left, then right. A right-to-left transfer still uses that order. Both balances change only after acquiring both monitors. Replace the first program with this one:

using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Threading;

object left = new();
object right = new();
int leftBalance = 1000;
int rightBalance = 1000;
var errors = new ConcurrentQueue<Exception>();

void Enter(object gate, CancellationToken token)
{
    var elapsed = Stopwatch.StartNew();
    while (true)
    {
        token.ThrowIfCancellationRequested();
        if (Monitor.TryEnter(gate, 20)) return;
        if (elapsed.ElapsedMilliseconds >= 5000)
            throw new TimeoutException("Lock acquisition exceeded five seconds.");
    }
}

void Transfer(bool leftToRight, CancellationToken token,
              ManualResetEventSlim? firstHeld = null)
{
    // Direction changes the data update, never the acquisition order.
    Enter(left, token);
    try
    {
        firstHeld?.Set(); // Test instrumentation only.
        Enter(right, token);
        try
        {
            token.ThrowIfCancellationRequested();
            int delta = leftToRight ? 1 : -1;
            leftBalance -= delta;
            rightBalance += delta;
        }
        finally { Monitor.Exit(right); }
    }
    finally { Monitor.Exit(left); }
}

void RunTransfers(bool direction)
{
    try
    {
        for (int i = 0; i < 100; i++)
            Transfer(direction, CancellationToken.None);
    }
    catch (Exception error) { errors.Enqueue(error); }
}

void Join(Thread a, Thread b)
{
    bool joinedA = a.Join(10000);
    bool joinedB = b.Join(10000);
    if (!joinedA || !joinedB) throw new TimeoutException("Worker did not stop.");
    if (errors.TryDequeue(out Exception? error))
        throw new Exception("Worker failed.", error);
}

for (int round = 0; round < 25; round++)
{
    var a = new Thread(() => RunTransfers(true)) { IsBackground = true };
    var b = new Thread(() => RunTransfers(false)) { IsBackground = true };
    a.Start();
    b.Start();
    Join(a, b);
    if (leftBalance != 1000 || rightBalance != 1000)
        throw new Exception("Balance assertion failed.");
}
Console.WriteLine("Ordered transfers: 5000; balances: 1000, 1000");

using var firstHeld = new ManualResetEventSlim();
using var cancel = new CancellationTokenSource();
bool cancelled = false;
var waiting = new Thread(() =>
{
    try { Transfer(true, cancel.Token, firstHeld); }
    catch (OperationCanceledException) when (cancel.IsCancellationRequested)
    {
        cancelled = true;
    }
    catch (Exception error) { errors.Enqueue(error); }
}) { IsBackground = true };

// Hold right so the worker must wait while owning left.
lock (right)
{
    waiting.Start();
    if (!firstHeld.Wait(5000)) throw new TimeoutException("No first lock.");
    cancel.Cancel();
    if (!waiting.Join(10000)) throw new TimeoutException("Cancellation failed.");
}
if (errors.TryDequeue(out Exception? failure))
    throw new Exception("Cancellation worker failed.", failure);
if (!cancelled || leftBalance != 1000 || rightBalance != 1000)
    throw new Exception("Cancellation changed balances or was not observed.");

foreach (object gate in new[] { left, right })
{
    bool taken = false;
    try
    {
        Monitor.TryEnter(gate, 1000, ref taken);
        if (!taken) throw new Exception("A lock leaked.");
    }
    finally
    {
        if (taken) Monitor.Exit(gate);
    }
}
Console.WriteLine("Cancelled while contended; balances unchanged");
Console.WriteLine("Workers joined; both locks released");
Ordered transfers: 5000; balances: 1000, 1000
Cancelled while contended; balances unchanged
Workers joined; both locks released

Both directions call the same acquisition routine. A worker waiting for left owns neither monitor; a worker holding left can wait for right, but another transfer cannot own right while waiting for left. That removes the demonstrated cycle. Microsoft’s Lock class guidance explicitly recommends consistent acquisition order across all paths that take the same locks.

The test runs 25 pairs of workers, each making 100 transfers: 5,000 transfers altogether. After every pair joins, it asserts that both balances are back to 1,000. These are modest integer counters for demonstrating synchronization, rather than a financial transaction design. The repetitions exercise the implementation; the ordering argument explains why this particular cycle cannot occur. They do not prove fairness or exclude unrelated deadlocks elsewhere.

Cancel while the second lock is unavailable

The final test deliberately holds right on the main thread. The worker acquires left and signals the test event. Only then does the main thread request cancellation and wait for the worker. Cancellation can be observed just before the first second-lock attempt or after a timed attempt; the test does not require a particular scheduling interleaving. In either case, the second resource is unavailable, neither balance changes, and the outer finally releases left.

Monitor.TryEnter has no cancellation-token parameter. Enter therefore checks the token between 20-millisecond attempts and fails after a five-second acquisition budget. These are test budgets, not real-time guarantees: scheduling can delay observation. The budget applies separately to each lock acquisition. A token check immediately before the balance update also catches cancellation noticed after both locks were acquired.

As Microsoft’s cooperative cancellation model explains, requesting cancellation does not forcibly stop another thread. A request racing after the final token check may allow the tiny update to finish; cancellation is not a rollback guarantee. This fixture checks the specifically arranged cancellation path, joins the worker, and reacquires both monitors after the main thread has released right.

Apply the ordering rule throughout the component

Document the order beside the shared resources and review every path that can hold more than one lock. For a variable set of resources, design a stable, unique ordering key shared by all callers. Transfer direction and caller-dependent argument order are unsuitable ordering rules. Avoid unrelated blocking work or callbacks while holding these locks: those can introduce dependencies outside this two-monitor proof.

These examples deliberately use dedicated object monitors so that timed acquisition and ownership flags are visible. Modern C# also supports System.Threading.Lock, introduced for this use with .NET 9 and C# 13. The compiler handles a statically typed Lock differently from an ordinary object monitor, as the lock statement reference explains. Changing the lock type does not repair an inconsistent acquisition order; do not treat the two locking mechanisms as interchangeable.

If the cleanup structure is unfamiliar, review C# exception handling and methods. For an actual hang, record which locks each thread owns and awaits, then check whether every nested acquisition respects the documented order.

Share This