CS Fundamentals Trainer · Guides
async/await in C#: what the compiler does, deadlocks and the rules that keep it safe
How an async method becomes a state machine, what Task and ValueTask are, why .Result and .Wait() can deadlock, when ConfigureAwait matters, how to run work concurrently with Task.WhenAll, cancellation with CancellationToken, and the async void trap - with the rules stated plainly and the cases that depend on the runtime flagged.
4 min read
async and await let you write code that waits for I/O without blocking a thread, in a shape that reads like synchronous code. They work by rewriting your method, and most of their pitfalls follow directly from that rewrite.
What the compiler does
An async method that contains await is compiled into a state machine. Code runs synchronously up to the first await on an operation that is not yet complete. At that point the method returns a Task to its caller and registers "run the rest of me when this finishes". When the awaited operation completes, the remainder (the continuation) runs, possibly on a different thread.
Two consequences:
awaitdoes not start a thread. The operation (a socket read, a delay) is usually driven by the operating system; no thread is held while it waits. That is the whole point: a web server can have thousands of requests in flight on a few threads.- An
asyncmethod runs on the caller's thread until its first real suspension. If nothing is awaited that is incomplete, the whole method runs synchronously.
async Task<string> LoadAsync(HttpClient http, string url)
{
var response = await http.GetAsync(url); // thread is released here
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
Task, Task<T> and ValueTask<T>
A Task represents work that completes later, successfully, with an exception or cancelled. Task<T> carries a result. ValueTask<T> avoids an allocation when a result is often available immediately (a cache hit); the price is rules: await it once, do not await it concurrently, and do not use it after it has completed. Default to Task<T> and reach for ValueTask<T> only when profiling shows allocations on a hot path.
Do not block on async code
task.Result, task.Wait() and task.GetAwaiter().GetResult() block the current thread until the task finishes. That is a problem for two reasons:
- Thread starvation. Every blocked thread is a thread that cannot serve other requests.
- Deadlock where a
SynchronizationContextexists (classic ASP.NET, WinForms, WPF). The continuation of the awaited method wants to run on the UI or request context, but that context's only thread is the one blocked in.Result. Neither can proceed. ASP.NET Core has no such context, so the same code usually "works" there, but still wastes threads.
The rule is "async all the way": if a method calls an async method, make it async too and await the call, up to the entry point (Main can be async Task Main).
ConfigureAwait(false)
await task.ConfigureAwait(false) says "I do not need to resume on the captured context". In library code it avoids the deadlock above and some overhead, so it is the usual convention there. In application code on ASP.NET Core there is no context to capture, so it makes no difference; in UI code you usually want the context back after an await, so leave it off.
Concurrency: start first, await later
Awaiting each call in turn runs them one after the other. To run them at the same time, start all of them and then await them together.
var a = LoadAsync(http, urlA); // started
var b = LoadAsync(http, urlB); // started
string[] results = await Task.WhenAll(a, b);
Task.WhenAll completes when all are done. If several fail, await rethrows the first exception; the others are still available on the Task.Exception property (an AggregateException). Task.WhenAny returns the first to finish, which is how you build timeouts and "first response wins". To limit concurrency use SemaphoreSlim or Parallel.ForEachAsync with MaxDegreeOfParallelism.
Cancellation
Pass a CancellationToken down through every async call and check it in loops. Cancelling is cooperative: nothing stops the work unless the code observes the token.
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
try { await LoadAsync(http, url, cts.Token); }
catch (OperationCanceledException) { /* timed out or cancelled */ }
In ASP.NET Core, an action that accepts a CancellationToken parameter gets one that is cancelled when the client disconnects.
async void
async void methods cannot be awaited, and an exception that escapes one is raised on the context and typically crashes the process. Use it only for event handlers. Everything else returns Task.
Other traps
- Fire and forget. Calling an async method without
awaitloses its exceptions and its completion. If you really mean it, handle errors inside, and prefer a hosted background service or queue. Task.Runis for CPU work. Wrapping an already-async call inTask.Runjust burns a thread-pool thread. Use it to move CPU-bound work off a UI thread, not to "make something async".asyncin alock. You cannotawaitinside alockstatement. UseSemaphoreSlim.WaitAsync()instead.- Disposal.
await usingandIAsyncDisposableexist for resources that clean up asynchronously. - Async streams.
IAsyncEnumerable<T>withawait foreachmodels a sequence that arrives over time.
Checklist
- Async all the way down; never
.Resultor.Wait(). Task/Task<T>return types,async voidonly for event handlers.- Start independent work first, then
Task.WhenAll. - Pass a
CancellationTokenthrough. ConfigureAwait(false)in libraries.
Sources
- Microsoft Learn: Asynchronous programming with async and await.
- Microsoft Learn: Task asynchronous programming (TAP) model.
- Stephen Cleary: Don't block on async code.
Practise this topic: C# & .NET C# & .NET › Concurrency