In C#, what must a type provide for await to accept it, and in what order does compiled code call a custom awaiter's members?
answer
- a pattern, not an interface
- GetAwaiter, even as an extension
- IsCompleted, then maybe OnCompleted
- GetResult returns or throws
- INotifyCompletion is the one interface
basics
~20 sawait is pattern-based: the type needs an accessible GetAwaiter() method, instance or extension, whose awaiter has a bool IsCompleted, a GetResult() method and implements INotifyCompletion. Compiled code calls IsCompleted, then OnCompleted only if unfinished, then GetResult.
solid answer
~40 sC# matches `await` against a **pattern**. The expression's type needs an accessible parameterless `GetAwaiter()`, and an extension method counts, so `await TimeSpan.FromSeconds(1)` works once someone declares one. The awaiter must have a `bool IsCompleted` property, a `GetResult()` method whose return type becomes the value of the `await`, and implement `INotifyCompletion` (`OnCompleted(Action)`), optionally `ICriticalNotifyCompletion` (`UnsafeOnCompleted(Action)`). The compiled code calls `GetAwaiter()`, reads `IsCompleted`; if `true` it calls `GetResult()` at once. If `false` it saves the awaiter and the builder passes a continuation to `UnsafeOnCompleted` when available, otherwise `OnCompleted`; the method returns, and when the awaiter invokes the continuation, `MoveNext` resumes and calls `GetResult()`, which returns the value or throws the failure. The awaiter decides on which thread that continuation runs.
code
csharp · 34 linesusing System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
var ready = new CacheSlot<string>();
ready.Fill("cached value");
Console.WriteLine(await ready); // IsCompleted is true: no OnCompleted call
var pending = new CacheSlot<string>();
_ = Task.Run(async () => { await Task.Delay(100); pending.Fill("loaded value"); });
Console.WriteLine(await pending); // IsCompleted is false: OnCompleted, then GetResult
class CacheSlot<T>
{
private T? _value;
private bool _filled;
private Action? _continuation;
public void Fill(T value)
{
_value = value;
_filled = true;
_continuation?.Invoke(); // resume the suspended async method
}
public Awaiter GetAwaiter() => new(this);
public readonly struct Awaiter(CacheSlot<T> slot) : INotifyCompletion
{
public bool IsCompleted { get { Console.WriteLine(" IsCompleted"); return slot._filled; } }
public void OnCompleted(Action continuation) { Console.WriteLine(" OnCompleted"); slot._continuation = continuation; }
public T GetResult() { Console.WriteLine(" GetResult"); return slot._value!; }
}
}go deeper
Recall that await works on anything with a GetAwaiter method, not only on Task.
Explain the awaiter members, the IsCompleted fast path, and why GetResult is where results and exceptions come back.
Show what a correct custom awaiter must guarantee: one continuation call, the completion race, failures through GetResult, and a deliberate choice of resume thread.
Judge when a custom awaitable earns its maintenance cost versus wrapping callbacks in TaskCompletionSource<T>, and who on the team can review such code.
## await is a pattern, not an interface The C# compiler does not ask whether a type implements some `IAwaitable`; no such interface exists. It looks for members by shape, the way `foreach` looks for `GetEnumerator`. For `await expr` to compile: 1. `expr`'s type must have an accessible **`GetAwaiter()`** method with no arguments. It can be an instance method or an **extension method**. 2. The returned **awaiter** type must have a readable `bool IsCompleted` property. 3. The awaiter must have a **`GetResult()`** method. Its return type is the type of the whole `await` expression (`void` for an await that produces nothing). 4. The awaiter must implement **`INotifyCompletion`**, whose single method is `OnCompleted(Action continuation)`. It may also implement **`ICriticalNotifyCompletion`**, which adds `UnsafeOnCompleted(Action continuation)`. `Task`, `Task<T>`, `ValueTask`, `Task.Yield()`'s `YieldAwaitable` and `ConfigureAwait`'s configured awaitables all satisfy the same pattern; there is nothing special about them at the language level. ## What the compiler says when the pattern is broken | Missing piece | Compiler output (C# 14) | |---|---| | no `GetAwaiter` on `int` | CS1061: 'int' does not contain a definition for 'GetAwaiter'... | | awaiter without `IsCompleted` | CS0117: 'Slot.Awaiter' does not contain a definition for 'IsCompleted' | | awaiter without the interface | CS4027: 'Slot.Awaiter' does not implement 'INotifyCompletion' | The last row surprises people: an awaiter with a perfect `OnCompleted(Action)` method is still rejected until it declares `INotifyCompletion`. ## The call order at run time For each `await`, the generated `MoveNext` does this: 1. Call `GetAwaiter()` once and keep the awaiter. 2. Read `IsCompleted`. 3. If it is `true`, call `GetResult()` immediately and continue. `OnCompleted` is never called. 4. If it is `false`, store the awaiter in a field, record the state, and ask the method builder to schedule the continuation. The builder calls the awaiter's `UnsafeOnCompleted` if it implements `ICriticalNotifyCompletion`, otherwise `OnCompleted`, passing an `Action` that re-enters `MoveNext`. Then `MoveNext` returns. 5. When the awaiter invokes that `Action`, `MoveNext` resumes after this await and calls `GetResult()`, which returns the value or **throws** the operation's exception. The difference between the two registration methods is the **ExecutionContext**: `TaskAwaiter.OnCompleted` flows it to the continuation, while `UnsafeOnCompleted` does not, because the async method builder already captures and restores it itself. ## The built-in awaitables follow the same rules - `TaskAwaiter` and `TaskAwaiter<TResult>` implement `ICriticalNotifyCompletion`; their `IsCompleted` simply forwards to the task's `IsCompleted`. - `ConfigureAwait(false)` returns a `ConfiguredTaskAwaitable` whose `ConfiguredTaskAwaiter` is another implementation of the same pattern, differing mainly in whether the continuation returns to the captured context. - `Task.Yield()` returns a `YieldAwaitable` whose `YieldAwaiter.IsCompleted` is always `false`, which is exactly how it forces the method to suspend. None of these get special treatment from the compiler; the method builder only recognizes some of them at run time to avoid allocating a delegate. ## Writing a custom awaiter that is actually correct The example below shows the protocol with a `CacheSlot<T>` that is either already filled or filled later. A production awaiter must also get these right: - **Invoke the continuation exactly once.** Never calling it leaves the async method suspended forever: its `Task` never completes and its `finally` blocks never run. Calling it twice re-enters the state machine when it does not expect it, with unpredictable results. - **Handle the race** between `IsCompleted` returning `false` and `OnCompleted` being called. If the result arrives in between, the awaiter must still run the continuation; the simple example does not guard against that. - **Report failure from `GetResult`**, by throwing, so `try`/`catch` around the `await` sees it. - **Choose where the continuation runs.** The thread that invokes the `Action` runs the rest of the method. `TaskAwaiter` captures a `SynchronizationContext` (the lesson on contexts covers this); a custom awaiter does whatever its author wrote. ## When custom awaitables are worth it They are rare in application code. Real uses include adapting a callback-based API, making a domain type awaitable through an extension `GetAwaiter`, and libraries that need zero-allocation awaits on a hot path. Usually wrapping the callback in a `TaskCompletionSource<T>` is simpler and handles the races for you.
- How can you make an existing C# type such as TimeSpan awaitable without changing it?Declare an extension method `GetAwaiter` for it, for example `public static TaskAwaiter GetAwaiter(this TimeSpan delay) => Task.Delay(delay).GetAwaiter();`. The awaitable pattern accepts extension methods, so `await TimeSpan.FromSeconds(1);` then compiles anywhere that extension's namespace is imported.
- What happens to a C# async method if a custom awaiter stores the continuation but never invokes it?The method stays suspended forever. Its `Task` never completes, anything awaiting it waits forever, and its `finally` blocks never run. Once nothing references the suspended state machine, the garbage collector can reclaim it without ever resuming it.
- Why does the builder prefer UnsafeOnCompleted when a C# awaiter implements ICriticalNotifyCompletion?The async method builder already captures the `ExecutionContext` and restores it around `MoveNext`. `OnCompleted` would flow the same context a second time, as `TaskAwaiter.OnCompleted` does, so `UnsafeOnCompleted` skips that redundant work.
- A type must implement an IAwaitable interface before it can be awaited.
- Only Task, Task<T> and ValueTask can be used with await.
- OnCompleted is called on every await, even when the result is ready.
- Matching method names is enough; INotifyCompletion is optional.
- A custom awaiter's continuation always resumes on the thread pool.