C# Reference ยท Async and Concurrency
async and await in depth
How C# async and await work under the hood: the compiler state machine, awaiters, the synchronous start, resumption and writing a custom awaitable.
This page explains what the compiler does with async and await. The keywords are covered on async and await; here we look at the mechanism so that behavior such as "why did my code run on another thread?" or "why did this throw late?" makes sense.
An async method is rewritten into a struct (a state machine) with a MoveNext method. Each await becomes a checkpoint: the compiler asks the awaited object for an awaiter, checks whether it is already complete, and if not, registers the rest of the method as a continuation and returns to the caller.
// What `await x` roughly does var awaiter = x.GetAwaiter(); if (!awaiter.IsCompleted) { // save state, register the continuation, return to the caller } var result = awaiter.GetResult(); // resume here; rethrows exceptions
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
The pieces the compiler looks for:
// The awaited expression needs: TAwaiter GetAwaiter(); // The awaiter needs: bool IsCompleted { get; } void OnCompleted(Action continuation); // from INotifyCompletion TResult GetResult(); // void for Task // Optionally ICriticalNotifyCompletion.UnsafeOnCompleted for faster scheduling
| Piece | Description |
|---|---|
GetAwaiter() |
Can be an instance or an extension method, so you can make existing types awaitable. |
IsCompleted |
When true, the method continues synchronously without leaving the stack. |
OnCompleted / UnsafeOnCompleted |
Registers the continuation the compiler built for the rest of the method. |
GetResult() |
Produces the value or rethrows the exception. It is called once, on the resuming path. |
| Builder | AsyncTaskMethodBuilder (and AsyncValueTaskMethodBuilder, AsyncIteratorMethodBuilder) turn the method result into a Task/ValueTask. |
Errors: an exception inside the method is captured by the builder and stored in the returned task. It does not escape from the call; it surfaces at the await.
Usage notes
- No new thread is created.
awaitdoes not start a thread. The continuation runs wherever the awaited operation or the captured context decides, normally a thread-pool thread in a console or ASP.NET Core app. - Everything before the first incomplete await is synchronous. That includes argument validation. An exception thrown there still ends up in the returned task for
asyncmethods; use a non-async wrapper if you want validation exceptions to surface at the call. - Each async method allocates its state machine on the heap the first time it truly suspends (an optimization avoids it when it completes synchronously). Hot paths may benefit from
ValueTaskor from avoiding trivially wrapping methods. - A return statement compiles to
SetResult; missing areturnin aTask<T>method is a compile error. awaitis allowed incatchandfinallyblocks (since C# 6) but not inside alockstatement or an unsafe context.- Locals are hoisted. Variables that live across an
awaitbecome fields of the state machine, soreflocals andSpan<T>cannot be used across an await. Since C# 13 you may declare them in an async method as long as they are not live at an await. - Awaiting a
Taskcaptures the currentSynchronizationContextor scheduler. See ConfigureAwait and SynchronizationContext. - Prefer returning the task directly (
return inner.Foo();) from thin wrappers that add no logic; but keepasync/awaitwhen you useusing,tryorcatcharound the call.