What await Actually Compiles To: Inside the C# Async State Machine

await is the least suspicious keyword in C#. It reads like “pause here, continue when the result arrives,” and for most day-to-day work that mental model is enough. But every async method you write is quietly dismantled by the compiler and rebuilt as something quite different: a state machine struct with a jump table, a builder object, and a heap allocation that only happens if the method actually suspends. Understanding that rewrite explains most real-world async behavior — why .Result deadlocks, why stack traces look mangled, where allocations come from, and what changes in .NET 11’s runtime async.

This post walks through what the compiler actually generates for an async method, the awaiter contract that makes await work on any type, how execution context flows across suspension points, and why the whole model is about to change.

The rewrite: one method becomes a struct and a loop

Take a method like this:

public async Task<string> FetchNameAsync(HttpClient client)
{
    var resp = await client.GetAsync("/api/name");
    var body = await resp.Content.ReadAsStringAsync();
    return body.Trim();
}

The compiler throws away this method body and generates a state machine — a struct (a class only if the method is the entry point of an iterator-like scenario or captures state it can’t keep in a struct) that contains:

private struct <FetchNameAsync>d__0 : IAsyncStateMachine
{
    public int <>1__state;                       // where we are
    public AsyncTaskMethodBuilder<string> <>t__builder;
    public HttpClient client;                    // parameters become fields
    public HttpResponseMessage <resp>5__1;       // locals that live across awaits
    public TaskAwaiter<HttpResponseMessage> <>u__1;  // the awaiter in flight
    // ... MoveNext() and SetStateMachine()
}

The original body is compiled into MoveNext(), a giant switch on the state field. State starts at -1 (not started). Each await becomes a checkpoint: when the awaited thing isn’t finished, the method stores its position in the state field, registers a callback with the awaiter, and returns — back to the caller, releasing the thread. When the awaited operation completes, the builder invokes MoveNext() again, the switch jumps to the label right after that await, and execution resumes. The state field is also how exceptions get routed: instead of a normal return, SetException parks the exception in the eventual Task.

Two consequences follow immediately. First, locals that survive across an await get hoisted into fields — that’s why you can’t use them in a lock statement across an await, and why closures inside async methods sometimes allocate more than you’d expect. Second, the “method” you call is really a stub that creates the state machine, calls builder.Start(<>t__stateMachine), and returns <>t__builder.Task. Start runs MoveNext() synchronously right away, on the caller’s thread — more on why that matters below.

The awaiter contract: await works on anything shaped like this

await is not tied to Task. It’s a pattern: any type exposing IsCompleted, GetResult(), and OnCompleted(Action) (or the builder-optimized UnsafeOnCompleted) can be awaited. That’s why ValueTask, Task.WhenAny results, and custom awaitable types all work without special compiler support.

Each await expression lowers to roughly this shape:

var awaiter = someTask.GetAwaiter();
if (awaiter.IsCompleted)
{
    // fast path: keep executing inline, no suspension at all
    result = awaiter.GetResult();
}
else
{
    <>1__state = 1;                 // remember where we paused
    builder.AwaitUnsafeOnCompleted(ref awaiter, ref this);
    return;                          // thread goes back to the caller
    // on completion, MoveNext() re-enters at state 1:
    // label:
    result = awaiter.GetResult();
}

The synchronous fast path is the whole reason ValueTask exists. If a method completes synchronously — a cached lookup, a read from a buffered stream — no suspension ever happens, no callback is registered, and with ValueTask there’s no Task allocation either. A hot path that’s “sometimes async” pays nothing on its synchronous runs. The caveat: a ValueTask must be awaited exactly once. Awaiting twice, or awaiting after the underlying object was reused, is undefined behavior in practice.

The heap allocation story is similar. The state machine starts life as a struct on the stack. Only if it actually suspends does the runtime copy it to the heap — once — so the continuation has something to survive the method’s stack frame. The boxed copy persists for the rest of the method; fields are updated in place afterward. A method with zero suspensions allocates only the Task it returns. This is why “async all the way down” was cheaper than its reputation suggested, and why frameworks like ASP.NET Core bother with Task.CompletedTask-style caching in a few corner cases.

Two contexts, one deadlock factory

When an await suspends, two pieces of ambient state matter: the ExecutionContext (which carries AsyncLocal<T> values — this is how tracing libraries propagate span context through await chains) and the SynchronizationContext (which decides where the continuation runs).

The builder distinguishes them at the call sites: AwaitOnCompleted is used when a SynchronizationContext is present, and it captures the context so the continuation can be Posted back to it. AwaitUnsafeOnCompleted is used when there’s no context (or you wrote ConfigureAwait(false)) and the continuation simply gets queued to the thread pool. This is the entire mechanism behind ConfigureAwait.

The classic deadlock falls straight out of this. On classic ASP.NET (or desktop UI frameworks), a SynchronizationContext exists. Write this:

// request thread, context present:
var value = DoSomethingAsync().Result;   // blocks the thread!

// inside DoSomethingAsync, at the first incomplete await:
// continuation is Posted back to the request thread's context,
// but that thread is blocked in .Result
// → the continuation never runs, the Task never completes, deadlock.

On ASP.NET Core there is no SynchronizationContext, so blocking on a task is “only” a wasted thread rather than a deadlock — but the modern takeaway is unchanged: never block on async code. Also note that ExecutionContext still flows regardless of ConfigureAwait(false); ConfigureAwait only affects the synchronization context, not AsyncLocal propagation. Tracing doesn’t break with ConfigureAwait(false), which is a widespread misconception.

Reading the artifacts: stack traces and attributes

Once you know the rewrite, async artifacts stop looking like noise. A stack trace showing MoveNext and AsyncMethodBuilderCore.Start frames is the state machine infrastructure appearing on the live stack — each async method contributes roughly double its real frames. The <>d__0-style names and the <>u__1 awaiter fields you see in dumps are the generated struct. And the [AsyncStateMachine(Type)] attribute on the stub method exists precisely so tooling can walk from the public stub to its machine.

What changes with runtime async in .NET 11

.NET 11 ships Runtime Async — the suspension mechanism moves from compiler-generated state machines into the runtime itself. With the opt-in runtime-async=on feature, the C# compiler no longer rewrites async methods at all; the runtime tracks suspended continuations natively. Live stack traces collapse to the real call chain (the documented example goes from 13 frames to 5), the debugger steps through awaits cleanly, and NativeAOT and ReadyToRun are supported. The runtime’s own libraries are compiled with the feature on, and per-project opt-out is a single property (<UseRuntimeAsync>false</UseRuntimeAsync>).

Your source code doesn’t change — await means the same thing. But the mental model of “compiler builds a jump table” becomes a legacy-mechanism fact rather than an eternal truth, which matters when you’re reading dumps, profilers, or decompiled code produced by older runtimes.

Wrapping up

Three things worth carrying forward: await is a compiler rewrite into a state machine with a synchronous fast path and a single heap copy on first suspension; the awaiter pattern (IsCompleted/GetResult/OnCompleted) is why ValueTask and custom awaitables work; and ConfigureAwait is about the SynchronizationContext, not about ExecutionContext or tracing. If you want to see the rewrite yourself, compile a small async method and inspect it with a decompiler — or read the runtime async announcement and see what your code looks like when nobody rewrites it at all.

Leave a Reply

Your email address will not be published. Required fields are marked *