C# Async Await: Deadlocks, Exceptions and Common Mistakes
Last updated: November 4, 2026 · Tested with .NET 10.0.12 (SDK 10.0.401), C# 14, ASP.NET Core 10.0.12, Windows 11
Short answer: C# async/await frees the thread while you wait for I/O, so await every task all the way up, and never block on one with .Result, .Wait() or .GetAwaiter().GetResult(). I reproduced the classic deadlock below: the same .Result call hangs forever on a UI-style thread and works in a console app and in ASP.NET Core. In ASP.NET Core it costs you something else instead: at 200 concurrent requests, throughput fell from 1,703 to 22 requests per second. The rest of this post covers async void crashes, Task.WhenAll exceptions, cancellation and throttling, each with the real output.
| Symptom | Cause | Fix |
|---|---|---|
| App freezes, no exception | .Result / .Wait() on a UI thread | await; ConfigureAwait(false) in libraries |
| Web API slow only under load, p50 in seconds | Sync-over-async starving the thread pool | Async all the way; no .Result in request code |
Process dies, try/catch didn’t help | Exception in an async void method | Return Task; async void only for event handlers |
| Only one of several errors logged | await Task.WhenAll rethrows the first | Read whenAllTask.Exception.InnerExceptions |
| Loop “finishes” instantly, work happens later | List.ForEach(async ...) or Parallel.ForEach(async ...) | foreach + await, or Parallel.ForEachAsync |
| Timeout fires but the work keeps running | Token not passed on, or WaitAsync | Pass the CancellationToken to every call |
| Every call made twice | Lazy Select enumerated twice | .ToArray() the tasks, or use the WhenAll result |
How I Tested It
Two projects. A console app runs each scenario and prints what happened and how long it took. A minimal API has an async endpoint and a sync-over-async endpoint, and the console app load-tests it over HTTP, with a fresh server process for every run so each starts with a cold thread pool. Every output block below is copied from those runs on a 14-logical-CPU laptop. Treat timings as comparisons, not benchmarks.
A console app has no SynchronizationContext, so the deadlock can’t happen there. To reproduce it without WinForms or WPF, I wrote a small context that does what a UI message loop does: one dedicated thread runs every posted callback in order.
public sealed class SingleThreadContext : SynchronizationContext
{
private readonly BlockingCollection<(SendOrPostCallback, object?)> _queue = new();
public override void Post(SendOrPostCallback d, object? state) => _queue.Add((d, state));
private void Run()
{
SetSynchronizationContext(this);
foreach (var (callback, state) in _queue.GetConsumingEnumerable())
callback(state);
}
}
Each test posts work to that thread and waits up to three seconds for it to finish. If nothing comes back in three seconds, it’s a deadlock: the thread never recovers.
The .Result Deadlock, Reproduced
static async Task<string> GetDataAsync()
{
await Task.Delay(100);
return "data";
}
console: SynchronizationContext.Current is null = True
console, GetDataAsync().Result -> "data" in 114 ms (no deadlock)
UI thread, GetDataAsync().Result -> DEADLOCK (nothing after 3011 ms)
UI thread, GetDataAsync().GetAwaiter().GetResult() -> DEADLOCK (nothing after 3013 ms)
UI thread, GetDataAsync().Wait() -> DEADLOCK (nothing after 3002 ms)
UI thread, ConfigureAwait(false) inside, .Result -> finished in 109 ms
UI thread, Task.Run(() => GetDataAsync()).Result -> finished in 110 ms
UI thread, await GetDataAsync() -> "data" in 109 ms
Here’s the sequence. The await inside GetDataAsync captures the UI context, so when the delay ends, the rest of the method is queued to the UI thread. But the UI thread is stuck inside .Result, waiting for that same method. Neither side can move.
Three things in that output surprise people:
.GetAwaiter().GetResult()deadlocks exactly like.Result. It only changes how the exception is thrown (the original exception instead of anAggregateException), not the blocking.- The identical call works in a console app. That’s why “it works on my machine” is common with this bug: the test ran in a console or test runner, the app runs on a UI thread or in old ASP.NET (System.Web), which also has a context.
- It works in ASP.NET Core too. Core has no
SynchronizationContext. I called the same.Resultin a minimal API endpoint:
GET /ctx -> SynchronizationContext.Current is null = True, GetDataAsync().Result = data
So the deadlock is gone in ASP.NET Core, but blocking is still a bug there. The next section shows the cost.
That also answers the most-viewed async question on Stack Overflow (1.4 million views): how to call an async method from a synchronous one. The honest answer is to make the caller async. When you really can’t, such as in an old interface you don’t own, Task.Run(() => GetDataAsync()).Result avoids the deadlock because the method starts on a pool thread with no context to return to. It still blocks a thread.
Sync-over-Async in ASP.NET Core: Thread-Pool Starvation
app.MapGet("/async", async () => await GetDataAsync());
app.MapGet("/sync", () => GetDataAsync().Result); // sync-over-async: blocks a pool thread for 100 ms
Both endpoints wait 100 ms, standing in for a database call. I expected /sync to be slower at any load. It wasn’t:
http://127.0.0.1:5080/async: 1000 requests, 14 concurrent, failed 0
total 7881 ms, 127 req/s, p50 109 ms, p95 111 ms, max 117 ms
http://127.0.0.1:5080/sync: 1000 requests, 14 concurrent, failed 0
total 7888 ms, 127 req/s, p50 109 ms, p95 112 ms, max 113 ms
With 14 concurrent requests and 14 minimum pool threads, every blocked request has its own thread, so there’s no difference. That’s the trap: it passes any test you run by hand. Raise the load past the pool size:
http://127.0.0.1:5080/async: 2000 requests, 200 concurrent, failed 0
total 1174 ms, 1703 req/s, p50 109 ms, p95 123 ms, max 137 ms
server: ThreadPool.ThreadCount = 14, min worker threads = 14
http://127.0.0.1:5080/sync: 2000 requests, 200 concurrent, failed 0
total 91478 ms, 22 req/s, p50 8133 ms, p95 18152 ms, max 28353 ms
server: ThreadPool.ThreadCount = 168, min worker threads = 14
Same code, same 100 ms of waiting: 1,703 against 22 requests per second, and a median of 8 seconds for a 100 ms call. The async version handled 200 concurrent requests with 14 threads. The blocking version pushed the pool to 168 threads and was still slow, because the runtime adds threads gradually once the minimum is used up, and every new thread was immediately blocked too. At 500 concurrent requests it stopped being slow and started failing:
http://127.0.0.1:5080/sync: 2000 requests, 500 concurrent, failed 1046
1046 x SocketException: No connection could be made because the target machine actively refused it.
More than half were refused at the TCP level, most likely because the starved server wasn’t accepting connections fast enough and the listen queue filled. The async endpoint at 500 concurrent served all 2,000 in 802 ms. I didn’t test raising the minimum with ThreadPool.SetMinThreads; it moves the point where this starts, it doesn’t remove the blocking. Microsoft has a guide to diagnosing thread-pool starvation with dotnet-counters if you suspect it in production. The usual offenders are .Result in a filter or constructor, and sync wrappers around HttpClient calls.
What ConfigureAwait(false) Actually Changes
UI thread id = 4
after await Task.Delay(50): thread 4, context is UI = True
after .ConfigureAwait(false): thread 6, context is UI = False
console main thread id = 2
console after await: thread 6 (thread pool, no context to return to)
On the UI thread, a plain await comes back to thread 4. With ConfigureAwait(false) the rest of the method runs on a pool thread, which is why it fixed the deadlock above. In a console app or ASP.NET Core there’s no context, so it changes nothing. My rule: use it in library code that might be called from a UI app, skip it in ASP.NET Core application code. Don’t use it after an await in UI code that then touches a control. The ConfigureAwait FAQ on the .NET blog covers the edge cases.
async void: try/catch Doesn’t Catch, the Process Dies
static async void SaveAsyncVoid()
{
await Task.Delay(50);
throw new InvalidOperationException("save failed (async void)");
}
The caller wraps it in try/catch and then waits a second:
SaveAsyncVoid() returned, the try block is done
UnhandledException event: save failed (async void), IsTerminating = True
Unhandled exception. System.InvalidOperationException: save failed (async void)
at System.Threading.ThreadPoolWorkQueue.Dispatch()
process exit code: 0xE0434352 (3762504530)
The method returned at its first await, so the try block finished before the exception existed. With no Task to put it in, the runtime rethrew it on a pool thread and the process exited. AppDomain.UnhandledException fired, but it can only log; IsTerminating is true. “still alive after 1 s” never printed. The same method returning Task, awaited:
caught: InvalidOperationException: save failed (async Task)
still alive
Keep async void for event handlers, and put a try/catch inside them. Watch for hidden async void too: an async lambda passed to a parameter of type Action is async void. More on exception handling in general in C# exception handling best practices.
The opposite mistake, a Task you never await, doesn’t crash. It’s worse:
_ = SaveAsyncTask();
500 ms later: no crash, no log, nothing
UnobservedTaskException: save failed (async Task)
after GC.Collect + WaitForPendingFinalizers
The exception only surfaced when the garbage collector finalized the task, and I had to force that. In a real app it may never appear. For background work in ASP.NET Core, use a hosted service with its own error handling. If it needs a scoped service such as a DbContext, see cannot consume scoped service from singleton.
Task.WhenAll Throws Only the First Exception
var all = Task.WhenAll(
Fail(50, new InvalidOperationException("A failed at 50 ms")),
Fail(100, new TimeoutException("B failed at 100 ms")),
slowOk);
try
{
await all;
}
await WhenAll caught: InvalidOperationException: A failed at 50 ms
caught after 310 ms (WhenAll waits for every task)
all.Exception is AggregateException with 2 inner exceptions:
InvalidOperationException: A failed at 50 ms
TimeoutException: B failed at 100 ms
.Wait() threw AggregateException: One or more errors occurred. (A failed at 50 ms) (B failed at 100 ms)
Two details. await unwraps the AggregateException and gives you only the first error; the second is still on the task, so keep a reference to the WhenAll task and log all.Exception.InnerExceptions. And WhenAll doesn’t fail fast: task A failed at 50 ms, but the catch ran at 310 ms, after the slow successful task. If you want to stop the others on the first failure, cancel a shared token.
Since .NET 8 you can wait without the throw and check afterwards:
await all3.ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing);
if (all3.IsFaulted)
SuppressThrowing: IsFaulted = true, errors = A failed at 50 ms | B failed at 100 ms
Sequential vs Concurrent, and the Lazy Select Trap
sequential await in foreach, 5 x 200 ms: 1023 ms
Task.WhenAll, 5 x 200 ms: 204 ms
start 3 tasks, then await one by one: 214 ms
lazy Select, WhenAll then tasks.Select(t => t.Result): 10 calls for 5 ids, 1219 ms
The first three lines are expected: independent calls run concurrently once you start them all before awaiting. You don’t need WhenAll for that; starting three tasks and awaiting them one by one took 214 ms too. WhenAll is still better, because it observes every exception.
The last line is a bug I’ve seen in code review:
IEnumerable<Task<int>> tasks = ids.Select(CallServiceAsync); // lazy!
await Task.WhenAll(tasks);
var values = tasks.Select(t => t.Result).ToList();
Select is lazy, so enumerating tasks a second time called the service again: 10 calls for 5 ids. And because the second round was read with .Result one at a time, it ran sequentially, so the whole thing took 1,219 ms instead of 200. Use the array that await Task.WhenAll(...) returns, or call .ToArray() on the tasks first.
ForEach(async …) Doesn’t Wait
items.ForEach(async i => { await Task.Delay(100); Interlocked.Increment(ref processed); });
List.ForEach(async ...) returned after 5 ms, processed = 0
300 ms later, processed = 10 (work ran after the caller moved on)
Parallel.ForEach(async ...) returned after 12 ms, processed = 0
await Parallel.ForEachAsync returned after 111 ms, processed = 10
plain foreach + await returned after 1098 ms, processed = 10
List.ForEach and Parallel.ForEach take an Action, so the async lambda becomes async void. They return as soon as each lambda hits its first await; the code after them sees nothing processed, and an exception in any item crashes the process as shown above. Use a plain foreach with await for sequential work, or Parallel.ForEachAsync for concurrent work.
Throttling: SemaphoreSlim or Parallel.ForEachAsync
Forty jobs of 100 ms each, with a counter recording how many ran at once:
unbounded Task.WhenAll: 40 jobs in 119 ms, max concurrent = 40
SemaphoreSlim(4): 40 jobs in 1096 ms, max concurrent = 4
Parallel.ForEachAsync, MaxDegreeOfParallelism = 4: 40 jobs in 1092 ms, max concurrent = 4
Parallel.ForEachAsync, default options: 40 jobs in 326 ms, max concurrent = 14
Unbounded WhenAll is fastest here, but with 4,000 items it would open 4,000 connections to whatever you’re calling. Both limits held exactly at 4. The last line is worth knowing: Parallel.ForEachAsync without options isn’t unbounded. It used 14, my processor count, which is the documented default for this method. For I/O, the right number depends on the remote service, not your CPU, so set it explicitly.
await Parallel.ForEachAsync(jobs, new ParallelOptions { MaxDegreeOfParallelism = 4 },
async (j, ct) => { using (meter.Enter()) await Task.Delay(100, ct); });
I use Parallel.ForEachAsync for a list of items and SemaphoreSlim when the limit has to be shared, for example one semaphore guarding an API across many requests. With SemaphoreSlim, always release in a finally.
Cancellation: Timings
token passed down: TaskCanceledException after 213 ms
token accepted but not passed on: finished normally after 2003 ms
WaitAsync(200 ms): TimeoutException after 202 ms
...the 2 s work still finished at 2012 ms
already-cancelled token: TaskCanceledException after 0 ms (the delay never started)
A 200 ms token stopped the work at 213 ms only when the method passed it on to Task.Delay. The method that accepted a token and didn’t use it ran the full 2 seconds. Accepting a CancellationToken parameter does nothing by itself.
Task.WaitAsync(timeout) is the trap: it threw TimeoutException at 202 ms, but the work behind it kept running and finished at about 2 seconds. It stops your wait, not the work. Also note the exception types: cancellation threw TaskCanceledException, so catch its base class OperationCanceledException, and treat TimeoutException from WaitAsync separately.
Checklist
awaitall the way up; no.Result,.Wait()or.GetAwaiter().GetResult()in request or UI code.- If you can’t avoid a sync call, use
Task.Run(...).Result, and know it still blocks a thread. - Load-test with more concurrent requests than
ThreadPoolminimum threads; sync-over-async hides below that. ConfigureAwait(false)in libraries; not needed in ASP.NET Core app code.- Return
Task, notvoid;async voidonly for event handlers, with atry/catchinside. - Don’t discard tasks; their exceptions disappear.
- Keep the
WhenAlltask and logException.InnerExceptions. - Materialize task lists with
.ToArray(). - No async lambdas in
List.ForEachorParallel.ForEach. - Throttle with
Parallel.ForEachAsyncorSemaphoreSlim, and set the limit explicitly. - Pass the
CancellationTokento every call;WaitAsyncdoesn’t cancel anything.
Related: runtime async in .NET 11 (benchmarks) · HttpClient in .NET 10 with IHttpClientFactory · C# exception handling best practices · Cannot consume scoped service from singleton · all C# tutorials