Async pitfalls
The async machinery has three traps that a first program meets. An async void method cannot be awaited, so its exception has nowhere to go. A blocking wait on a task, .Result or .Wait(), can deadlock when the continuation needs the thread that is waiting. And a library that captures the caller context pays for a switch it does not need. Each is shown with its real output.
async void
An async void method returns nothing to await, so the caller cannot catch its exception. The runtime raises it on the thread pool, where nothing handles it, and the process ends:
Console.WriteLine("before");
FireAndForget();
await Task.Delay(500);
Console.WriteLine("after");
static async void FireAndForget()
{
await Task.Delay(1);
throw new InvalidOperationException("from async void");
}
dotnet run
before
Unhandled exception. System.InvalidOperationException: from async void
at Program.<<Main>$>g__FireAndForget|0_0() in /tmp/csrun.x5f5mN/Program.cs:line 11
at System.Threading.Tasks.Task.<>c.<ThrowAsync>b__124_1(Object state)
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading.PortableThreadPool.WorkerThread.WorkerThreadStart()
at System.Threading.Thread.StartCallback()
Aborted (core dumped)
The program printed before and never reached after, because the exception killed it first. The trace has no caller frame: the method was started and forgotten, and the throw happened on the pool. The exit status of this run is 134, the abort of the lesson on unhandled exceptions. The one legitimate async void is an event handler, where the signature is fixed by the event and the framework catches what it can; everything else returns Task.
Result and Wait
task.Result and task.Wait() block the calling thread until the task finishes. On a completed task they are harmless, and on a failing task they throw an AggregateException that wraps the real one:
var ready = Task.FromResult(3);
Console.WriteLine($"result {ready.Result}");
var failing = Task.Run(() => throw new InvalidOperationException("worker"));
try
{
failing.Wait();
}
catch (AggregateException e)
{
Console.WriteLine($"caught {e.GetType().Name}");
Console.WriteLine($"inner {e.InnerException?.GetType().Name}: {e.InnerException?.Message}");
}
dotnet run
result 3
caught AggregateException
inner InvalidOperationException: worker
The await of the same task would have thrown InvalidOperationException directly, without the wrapper. The wrapper exists because Wait can wait for several tasks at once, and it is the reason a log from a blocking call shows one more exception type than a log from an await.
A deadlock that was measured
The dangerous case is a wait inside a context that runs the continuation. A single-threaded context is installed here, the async method captures it, and the main thread blocks on the task. The continuation can only run on that same thread, which is waiting, so the wait times out:
using System.Collections.Concurrent;
var context = new SingleThreadContext();
SynchronizationContext.SetSynchronizationContext(context);
var task = Work();
Console.WriteLine($"completed within 300ms {task.Wait(300)}");
context.Drain();
Console.WriteLine($"completed after drain {task.IsCompleted}");
Console.WriteLine($"result {task.Result}");
static async Task<int> Work()
{
await Task.Yield();
return 7;
}
sealed class SingleThreadContext : SynchronizationContext
{
private readonly ConcurrentQueue<(SendOrPostCallback Callback, object? State)> queue = new();
public override void Post(SendOrPostCallback d, object? state)
{
queue.Enqueue((d, state));
}
public void Drain()
{
while (queue.TryDequeue(out var item))
{
item.Callback(item.State);
}
}
}
dotnet run
completed within 300ms False
completed after drain True
result 7
The wait of three hundred milliseconds returned false: the task could not finish while the only thread that could run its continuation was inside Wait. Drain then ran the continuation by hand and the task completed with 7. A real program does not have a drain: a desktop UI thread or an ASP.NET request context is exactly this shape, and a .Result there deadlocks the request. The fix is not a longer timeout but await all the way to the top, which the entry point now supports.
ConfigureAwait
await task.ConfigureAwait(false) tells the runtime not to return to the captured context. A library uses it on every await, because the library does not care which thread continues and the caller does not want the switch. An application does not need it: the code after an await in an event handler or a controller wants the context back, and the default gives it.
- Never write async void outside an event handler.
- Never block on a task with .Result or .Wait() in a context that must run the continuation.
- A library awaits with ConfigureAwait(false); an application leaves the default.
- .GetAwaiter().GetResult() avoids the aggregate wrapper and keeps the deadlock.
Exercises
- Change the async void method to async Task and await it; the process survives and the catch prints the message.
- Replace task.Wait(300) with await task and confirm that no drain is needed.
- Add ConfigureAwait(false) to the Task.Yield of the deadlock program and see which thread the continuation takes.
- Call .Result on a task that is still running on the pool and observe that it does not deadlock, then explain why the context matters.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Why is async void dangerous?
Answer
Its exception cannot be caught by the caller and ends the process
Nothing awaits it, so the exception is raised on the pool with no handler.
-
What did the async void program print before it died?
Answer
before, and then the unhandled exception text
The first line printed, the throw ended the process, and after never ran.
-
What does this program print?
var ready = Task.FromResult(3); Console.WriteLine(ready.Result);Answer
3
The task is already complete, so Result returns its value at once.
-
What does task.Wait(300) return when the task is still running?
Answer
false, after waiting 300 milliseconds
The measured deadlock returned False and left the task incomplete.
-
What does this program print?
using System.Collections.Concurrent; var context = new SingleThreadContext(); SynchronizationContext.SetSynchronizationContext(context); var task = Work(); Console.WriteLine(task.Wait(300)); context.Drain(); Console.WriteLine(task.IsCompleted); static async Task<int> Work() { await Task.Yield(); return 7; } sealed class SingleThreadContext : SynchronizationContext { private readonly ConcurrentQueue<(SendOrPostCallback Callback, object? State)> queue = new(); public override void Post(SendOrPostCallback d, object? state) => queue.Enqueue((d, state)); public void Drain() { while (queue.TryDequeue(out var item)) { item.Callback(item.State); } } }Answer
False and then True
The wait cannot finish on the blocked thread; draining the queue completes the task.
-
What does ConfigureAwait(false) tell the runtime?
Answer
Do not return to the captured context after the await
A library does not need the caller context, and the caller does not want the switch.
-
What does this program print?
Console.WriteLine(Task.FromResult(3).Result);Answer
3
The completed task carries 3 and Result returns it.
-
Why is .Result in an async method a bug?
Answer
It blocks a thread and can deadlock on the context
The deadlock program is that bug in its smallest form.
-
What is the fix for a sync-over-async deadlock?
Answer
Await the task all the way to the top
Nothing blocks the context, so the continuation gets the thread it needs.
-
What does awaiting a faulted task throw, compared with Wait?
Answer
The original exception, not an AggregateException
The await unwraps the aggregate, which the two programs showed.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev