C# Reference ยท Async and Concurrency
Deadlocks
Understand deadlocks in C#: lock ordering, sync-over-async, how to detect them with timeouts, and the rules that prevent them in threaded and async code.
A deadlock is a state in which two or more pieces of work wait for each other forever, so none can continue. The program does not crash and does not throw; it simply stops making progress, which makes deadlocks hard to notice in tests and painful in production.
Every deadlock needs the same four ingredients: a resource that can be held by only one party at a time, a party that holds one resource while waiting for another, no way to take a resource away, and a cycle of waiters. Remove any one of them and the deadlock cannot happen. In C# the two common shapes are lock-order inversion between threads and sync-over-async (blocking on a task with .Result or .Wait()).
// Thread 1: lock (a) { lock (b) { ... } } // Thread 2: lock (b) { lock (a) { ... } } // opposite order: can deadlock
Try it
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.
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.
Causes and how to prevent them
Lock-order inversion
Two threads take the same locks in different orders. The cure is a global lock order: decide once that, for example, the account with the smaller id is always locked first, and follow that everywhere. When objects are not naturally ordered, you can order them by a stable id.
Sync-over-async
In an environment with a single-threaded SynchronizationContext (classic UI frameworks, old ASP.NET), code like this hangs:
// Read-only: blocks the context thread that the continuation needs string text = ReadAsync().Result;
The await inside ReadAsync wants to resume on the captured context, but that thread is blocked waiting for the result. The fix is to await all the way up (do not block), or in library code to use ConfigureAwait(false). ASP.NET Core and console programs have no such context, so the same code usually does not hang there, but it still wastes a thread and can starve the thread pool.
Thread pool starvation
Blocking waits inside pool work items can use up every worker thread; the work that would unblock them is queued behind them. This looks like a deadlock but resolves slowly as the pool adds threads.
Waiting while holding a lock
Calling unknown code (a callback, an event handler, a virtual method) while holding a lock invites cycles you cannot see. Copy what you need under the lock, release it, then call out.
Usage notes
- Use timeouts at the edges.
Monitor.TryEnter(obj, timeout),SemaphoreSlim.Wait(timeout)andTask.Wait(timeout)turn a silent hang into an error you can log. - Keep critical sections short and free of I/O, waiting and callbacks. The less you do under a lock, the fewer ways it can form a cycle.
lockcannot be used acrossawait. The compiler rejectsawaitinside alockstatement. UseSemaphoreSlim.WaitAsync()for async mutual exclusion.lockis re-entrant,SemaphoreSlim(1)is not. Calling code that takes the same semaphore twice on one flow deadlocks itself.- Prefer higher-level tools: immutable data,
Channel<T>, concurrent collections andInterlockedneed fewer locks, so there are fewer deadlock opportunities. - Diagnosing a hang: attach a debugger and look at the Parallel Stacks and Threads windows, or take a dump (
dotnet-dump) and look for threads waiting onMonitor.EnterorTask.Wait. Two threads each waiting on a lock the other holds is the signature. - There is no automatic detection in the runtime. A deadlock is found by design discipline, timeouts and diagnostics, not by an exception.