skip to content

What does the C# compiler generate for an async method, and what jobs do MoveNext, the state field and the method builder each do?

level: middleimportance: should knowfreq 40%

answer

  1. a stub plus a generated type
  2. IAsyncStateMachine and one MoveNext
  3. state -1 while running
  4. builder: Start, Task, SetResult, SetException
  5. locals live across await become fields

basics

~20 s

The compiler emits a state-machine type implementing IAsyncStateMachine and a stub method. MoveNext runs the body up to each suspension, the state field records which await to resume at, and the method builder starts it and completes the returned Task.

solid answer

~40 s

The compiler replaces the body with a **stub** and a generated type, a `struct` in Release builds and a `class` in Debug, that implements `IAsyncStateMachine`. Its fields are `<>1__state`, the builder (`AsyncTaskMethodBuilder<T>` for `Task<T>`), the parameters, `this` when used, awaiter fields and every local that must survive an `await`. The stub creates the machine, sets the state to -1, calls `builder.Start(ref machine)`, which runs `MoveNext` immediately, and returns `builder.Task`. `MoveNext` is the body split at each `await`: a jump on the state resumes at the right spot; at an unfinished await it stores the awaiter, sets the state to that await's number, calls `builder.AwaitUnsafeOnCompleted` and returns. At the end it calls `SetResult`; an exception goes to `SetException`, which faults the `Task`.

code

csharp · 23 lines
csharp
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;

MethodInfo m = typeof(PriceCache).GetMethod(nameof(PriceCache.GetPriceAsync))!;
Type sm = m.GetCustomAttribute<AsyncStateMachineAttribute>()!.StateMachineType;
Console.WriteLine($"{sm.Name}: {(sm.IsValueType ? "struct" : "class")}, implements {string.Join(", ", Array.ConvertAll(sm.GetInterfaces(), i => i.Name))}");
foreach (FieldInfo f in sm.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
    Console.WriteLine($"  {f.FieldType.Name,-28} {f.Name}");

class PriceCache
{
    public async Task<decimal> GetPriceAsync(string sku)
    {
        string key = sku.ToUpperInvariant();
        int attempts = 0;
        decimal price = await LoadAsync(key);
        attempts++;
        return price * attempts;
    }
    static Task<decimal> LoadAsync(string key) => Task.FromResult(9.99m);
}

go deeper

for a junior

Recall that the compiler turns an async method into a generated type with a MoveNext method, and that the original method becomes a small stub.

for a middle

Explain the stub's steps, the state field's values, the IsCompleted branch in MoveNext, and how the builder completes or faults the returned Task.

for a senior

Use the shape to reason about cost and behaviour: Release structs versus Debug classes, which locals are hoisted, and where exceptions are captured.

for a principal

Weigh when a custom or pooling builder, applied per method since C# 10, is worth the extra complexity compared with the default builders.

## The two pieces the compiler emits For every `async` method the C# compiler produces two things: - a **stub method** with your original signature, which no longer contains your code; - a **state-machine type**, nested in your class with an unspeakable name such as `<GetPriceAsync>d__0`, that implements `System.Runtime.CompilerServices.IAsyncStateMachine` (members `MoveNext()` and `SetStateMachine(IAsyncStateMachine)`). The method is also marked with `[AsyncStateMachine(typeof(...))]`, which is how debuggers and reflection find the generated type. In a **Release** build the type is a `struct`, so a call that never suspends needs no heap allocation for it; in a **Debug** build it is a `class`, which keeps every local visible to the debugger. ## The fields of the state machine | Field (Release build) | What it holds | |---|---| | `<>1__state` | -1 while running or before the first suspension; 0, 1, 2... for the await it is suspended at | | `<>t__builder` | the method builder, e.g. `AsyncTaskMethodBuilder<decimal>` for `Task<decimal>` | | parameters, `<>4__this` | copied in by the stub; `this` only when the body uses it | | `<name>5__N` | **hoisted locals**: locals whose value must survive an await | | `<>u__N` | the awaiter being waited on, kept so `GetResult` can be called after resuming | The Release build hoists only what crosses an await; a local used entirely before or entirely after a single await stays an ordinary local inside `MoveNext`. A Debug build hoists every local. ## What the stub and MoveNext do The stub method: 1. creates the state machine and copies the arguments in; 2. sets `builder = AsyncTaskMethodBuilder<T>.Create()` and `state = -1`; 3. calls `builder.Start(ref stateMachine)`, which calls `MoveNext()` right away on the current thread; 4. returns `builder.Task`. `MoveNext` is your body cut at every `await`. It begins with a jump on `<>1__state`, so a fresh call starts at the top and a resumed call jumps to the code after the right await. At each `await expr` it calls `expr.GetAwaiter()` and checks `IsCompleted`: - **already complete**: it calls `GetResult()` and keeps going, with no suspension; - **not complete**: it stores the awaiter in a field, sets the state to that await's number, calls `builder.AwaitUnsafeOnCompleted(ref awaiter, ref this)` (or `AwaitOnCompleted` when the awaiter only implements `INotifyCompletion`) and **returns**. When the operation finishes, the continuation calls `MoveNext` again, which restores the awaiter, sets the state back to -1 and calls `GetResult()`. The whole body sits inside a `try`/`catch`: reaching the end calls `builder.SetResult(value)`, and an exception escaping the body calls `builder.SetException(exception)`, which stores it in the returned `Task` rather than throwing it at the caller. ## What the method builder is for The **builder** connects the state machine to the type the method returns. It creates or reuses the `Task`, completes it, and on the first real suspension copies the struct state machine to the heap so it can outlive the stack frame. The compiler picks the builder from the return type: - `Task` uses `AsyncTaskMethodBuilder`, `Task<T>` uses `AsyncTaskMethodBuilder<T>`; - `void` uses `AsyncVoidMethodBuilder`; - `ValueTask` and other task-like types name their builder with `[AsyncMethodBuilder(typeof(...))]` on the type, and since C# 10 the attribute can also sit on a single method to override the builder for that method only. ## Seeing it for yourself You do not need to trust a diagram of the generated code; you can look at it: - **Reflection**, as in the example below: read `[AsyncStateMachine]` from the method and list the generated type's fields. Comparing a Debug run with a Release run shows the struct-versus-class difference and which locals are hoisted. - **An IL decompiler** with the option to show compiler-generated code reveals `MoveNext` itself: the jump on the state, the `IsCompleted` checks and the `try`/`catch` around the body. The names with angle brackets are deliberately unspeakable in C#, so your own code can never collide with them, and they are an implementation detail that can change between compiler versions. ## Why interviewers ask Knowing the shape explains several behaviours that otherwise look like magic: why an async method runs synchronously until its first unfinished await, why exceptions surface when the `Task` is awaited, why the return type decides which builder runs, and why a local of a `ref struct` type such as `Span<T>` cannot stay alive across an await.

  • Why does a C# Debug build emit the async state machine as a class while a Release build emits a struct?
    In Release the struct lets a call that completes synchronously avoid any heap allocation for the machine; the builder boxes it only on the first real suspension. Debug builds favour the debugger over speed: a class with every local hoisted keeps variables inspectable across awaits, at the cost of an allocation per call.
  • Why does a C# 14 async method reject a Span<int> local that is still used after an await?
    Locals that cross an await become fields of the state machine, which may be copied to the heap, and a `ref struct` such as `Span<T>` can never live there. Since C# 13 such locals are allowed when they do not cross an await; one that does gives CS4007, "Instance of type 'System.Span<int>' cannot be preserved across 'await' or 'yield' boundary."
  • How can one C# async method use a different builder from the one its return type names?
    Since C# 10, `[AsyncMethodBuilder(typeof(SomeBuilder<>))]` may be placed on the method itself, overriding the builder declared on the return type for that method only. The BCL's `PoolingAsyncValueTaskMethodBuilder<TResult>` is the common example, used on methods that return `ValueTask<TResult>`.

  • The compiler turns each await into a separate method or lambda.
  • Every local of an async method is moved to the heap in every build.
  • The state machine is always a heap-allocated class.
  • An exception in an async method's body is thrown straight to the caller of the stub.
  • MoveNext blocks the thread while the awaited operation is unfinished.

Assumes C# 14 on .NET 10; C# 13 started allowing ref struct locals in async methods as long as they do not live across an await.