10 — async/await and iterators
csharpc compiles async methods, iterators (yield return) and async iterators
(IAsyncEnumerable<T>) to LLVM coroutines. It uses the switch-resumed lowering, the same
machinery clang uses for C++20 coroutines. Roslyn’s IOperation/CFG doesn’t lower any of these:
await stays an IAwaitOperation inside expressions and yield return stays an
IReturnOperation (kind YieldReturn). The state machine is built by LLVM’s CoroSplit pass,
not by csharpc.
Code: src/Csharpc/CodeGen/Coroutines.cs (classification), FunctionCodeGen.Async.cs
(lowering), ModuleCodeGen.Async.cs (iterator method tables), src/runtime/async.c (tasks,
scheduler, iterator objects).
Lowering
The method itself is the coroutine “ramp” (it carries the presplitcoroutine attribute):
start: promise = csrt_task_new(sizeof T) ; async: the Task the caller receives
promise = csrt_iterator_new(MT, sizeof T, …) ; iterator: the IEnumerable<T> object
id = llvm.coro.id(16, null, null, null)
hdl = llvm.coro.begin(id, csrt_coro_alloc(llvm.coro.size.i64()))
[iterators: initial suspend; the body runs on the first MoveNext()]
await t: if (!csrt_task_is_completed(t)) { csrt_task_on_completed(t, hdl); suspend }
result = load T from t.payload ; completed tasks continue synchronously
yield v: it.current = v; it.state = 1; suspend ; destroy path runs pending finally blocks
return: task.payload = v -> finally blocks -> csrt_task_complete(task) -> coro.free -> coro.end
end: it.state = 2 (async iterator: complete the pending MoveNextAsync with false)
suspend: switch (llvm.coro.suspend(none, false)) { 0: resume, 1: cleanup, default: ret promise }
- Frames live on the GC heap. An async method’s frame shares one object with its task
(
csrt_coro_alloc_task: the task first, the frame after its payload), so a call allocates once; iterators get theirs fromcsrt_coro_alloc. Everything CoroSplit spills into the frame (locals, temporaries, the awaited task) is scanned by the conservative collector.llvm.coro.freefrees nothing. - Resuming from C. The split resume and destroy functions use
fastcc, so the runtime never callsframe[0]directly. Modules containing coroutines emit C-ABIcsrt_coro_resumeandcsrt_coro_destroywrappers aroundllvm.coro.resume/llvm.coro.destroy.src/runtime/async.chas weak fallbacks so programs without coroutines still link. - -O0. CoroSplit is mandatory, so the driver runs
default<O0>when the module contains coroutines and no other pipeline is requested. - Generics. Coroutines are monomorphized like any other generic code: element and result types go through the instantiation’s type substitution.
Runtime-async methods from IL
.NET 11 libraries (ASP.NET Core, System.Net.Http, parts of CoreLib) are compiled with runtime async:
a method marked MethodImplOptions.Async (0x2000) has no state machine; its IL returns the
unwrapped result (ret with a T for Task<T>, nothing for Task) and awaits by calling
System.Runtime.CompilerServices.AsyncHelpers.Await(task) (Await<T>, the ValueTask and
Configured*Awaitable overloads), or — for other awaiters — tests IsCompleted and calls
AsyncHelpers.UnsafeAwaitAwaiter(awaiter) / AwaitAwaiter(awaiter) before GetResult().
csharpc lowers such a method like a C# async method from source (FunctionCodeGen.RuntimeAsync.cs):
the same coroutine ramp, AsyncHelpers.Await(x) is await x, ret stores the result and
completes the task, an exception leaving every handler faults it, and a custom awaiter gets an
Action bound to the coroutine frame (csrt_coro_resume) through UnsafeOnCompleted/OnCompleted.
tests/il.sh runs IlAsyncApp’s whole async suite against IlRuntimeAsyncLib, the same library compiled
with <Features>runtime-async=on</Features>.
Tasks and the scheduler
Task, Task<T>, the non-generic ValueTask, the awaiters (TaskAwaiter, the non-generic
ValueTaskAwaiter, the Configured* ones, YieldAwaitable) and CancellationToken are all represented
by a pointer to one csrt task object (TypeMapper maps these library types to ptr):
{ mt, i32 state, i32 payload_size, conts, i32 ncont, i32 lock, exception, aggregate, i32 id, i32 flags, payload @ +56 }
Classes deriving from TaskCompletionSource(<T>) (System.Net.Http’s connection waiters, Kestrel’s) are laid
out over that struct (ModuleCodeGen.TaskSources.cs): the header, T’s payload at the fixed offset, then the
class’s own fields; the method table chains to csrt_Task_MT (so every task test accepts them, and
csrt_object_is_task walks the chain) and the base constructor stores the payload size. The task creation options
passed to base(...) are ignored, as for new TaskCompletionSource(options).
TaskModuleCodeGen.TaskTypes.cs). The code that
creates a Task<T> (an async method’s task, Task.FromResult, new TaskCompletionSource<T>(), Task.Run,
WhenAll/WhenAny, FromException<T>, a class deriving from TaskCompletionSource<T>) stores a per-T table in the
object’s header instead of csrt_Task_MT: same flags and Object virtuals, the name
System.Threading.Tasks.Task1[System.Int32], and csrt_Task_MTas its base class, sois Task, the await fast paths and csrt_object_is_task(which walk the chain) accept it unchanged andx is Task, (Task (InvalidCastExceptionwith .NET's message),as, patterns and List<Task's IListslots are identity tests like any class's. The one stored word is the whole cost of a typed task (an async method's allocation,Task.FromResultandnew TaskCompletionSourcestore it inline; nothing is called). It is pay for play in size: creation sites store a placeholder global, and only a program that can tell task types apart (a type test or cast against aTaskorTaskCompletionSource, typeof(Task, or GetType()on an object, interface or task) gets the tables defined (a name and 64 bytes perT, plus the type metadata); any other program has the placeholders replaced by csrt_Task_MTwhen code generation ends and emits nothing. The non-genericTaskandTask(what anasync Taskmethod,Task.Delayor a result-lessTaskCompletionSourcemake in .NET) are one type, the plain table, sois Task
What the tables don’t give: GetType() of a task an async method, WhenAll, ContinueWith… made is Task1[T], where .NET names an internal derived class (AsyncStateMachineBox...); the result of is/casts agrees, the class name doesn't. Task.CompletedTask.GetType()isTask(.NET:Task1[VoidTaskResult]). A Task<T> array doesn’t check stores through a
covariant object[] (the element table of a task array is empty), and x is TaskCompletionSource<T> is true of any
Task<T>, as a source is its task here.
ValueTask<T> is .NET’s struct (corelib/Tasks/ValueTaskOfT.cs, a port of .NET’s ValueTask<T>,
ValueTaskAwaiter<T> and ConfiguredValueTaskAwaitable<T>): { object _obj, T _result, short _token, bool _continueOnCapturedContext }, where _obj is null (the result is inline: a synchronously completed
ValueTask<T> allocates nothing), a csrt task, or an IValueTaskSource<T> called exactly as .NET calls it
(awaiting one twice is the source’s error, AsTask() makes one task, Preserve() keeps an inline result).
await of one (FunctionCodeGen.AwaitValueTask, also AsyncHelpers.Await<T> in runtime-async IL) tests
IsCompleted, then resumes the coroutine straight from the task (as await task does) or through the
source’s OnCompleted (csrt_coro_resume_token / csrt_coro_resume_state keep the await’s execution-context
flow), and reads GetResult(). An async method returning ValueTask<T> returns the struct over its task
(ValueTaskAwait<T>.OfTask), as does an async iterator’s MoveNextAsync(). In the TechEmpower server,
synchronous ValueTask<T> results (Pipe.ReadAsync, socket sends and receives) were 64 % of the tasks
allocated before.
(+40 on wasm32.) default(ValueTask) is a null pointer, meaning “completed”. id is Task.Id, assigned
on first use from one counter as in .NET; flags tells Task.Status a pending Task.Run delegate task
(WaitingToRun, then Running) from a promise-style one (WaitingForActivation).
flags also has the bits for Created (new Task, not started), WaitingForChildrenToComplete (a task whose
body is done while attached children aren’t) and “created by Task.Run” (Task.CreationOptions is
DenyChildAttach).
What the object has no field for lives in a ConditionalWeakTable keyed by the task
(corelib/Tasks/TaskState.cs), so only tasks that have it pay: Task.AsyncState and Task.CreationOptions
(recorded when a task is created with a state or non-default options: new Task, Task.Factory.StartNew,
ContinueWith, TaskCompletionSource(state, options)), and the ManualResetEvent behind
IAsyncResult.AsyncWaitHandle. A task implements IAsyncResult through slots csrt registers for its method
table (ModuleCodeGen.TaskAsyncResultMember); Task.Dispose only checks that the task has completed, as
.NET’s does. Task.Exception and the AggregateException that Wait()/Result throw are new objects on
every read (the task keeps only the inner-exception list), as in .NET; TaskCanceledException.Task is a
field of the exception (data in csrt_Exception) and its CancellationToken is the canceled task’s own.
The task object is the same csrt struct whatever its type: only the table pointer differs.
TaskFactory.ContinueWhenAll / ContinueWhenAny / FromAsync (corelib/Tasks/TaskFactoryOps.cs, the public
overloads in TaskFactoryMembers.cs; every overload .NET has on TaskFactory and TaskFactory<TResult>). A multi-task
continuation is a gate task over a private copy of the antecedents (completed when all, or the first in order, have
completed, whatever their outcome) that TaskSupport.ContinueWith hooks as for Task.ContinueWith: the factory’s
default token, continuation options and scheduler apply when the overload does not name them, a token canceled before
the antecedents finish cancels the continuation at once, NotOn*/OnlyOn* are rejected, and the argument checks keep
.NET’s exceptions, messages and order (which differs between All and Any). FromAsync over an IAsyncResult runs the
end method as a task: inline when the operation is complete (the scheduler is asked through TryExecuteTaskInline,
else QueueTask), otherwise from ThreadPool.RegisterWaitForSingleObject on its wait handle (so on WebAssembly, which
has no threads, an incomplete operation is PlatformNotSupportedException); an OperationCanceledException from the end
method cancels the task. Begin/End pairs call Begin at once (its exception propagates), complete the promise from the
callback or, for a CompletedSynchronously result, right after Begin returns, and AsyncState is the state argument.
Left out: the type identity of the returned tasks (GetType() names ContinuationResultTaskFromResultTask<,> etc.).
Threading model (.NET semantics for console apps, src/runtime/async.c):
- Thread pool.
Task.Runwork items run on a pool of background worker threads (processor-count workers, minimum 2; the count is the process’s CPU affinity, as .NET’s), concurrently with the caller. Pool threads never keep the process alive: whenMainreturns, the process exits. As in .NET, wake-ups are rationed: a worker that runs out of work polls the queue for up to 30 µs before sleeping, queueing wakes a sleeper only when no worker is polling, and a worker that takes an item while more wait wakes the next one.ThreadPool.QueueUserWorkItem& co. queue a one-argument delegate and its reference argument as they are (no closure). - Continuations. An
awaiton an already-completed task continues synchronously. Otherwise the coroutine registers itself as a continuation (the first one is stored in the task itself, further ones in an array) and is resumed by the thread that completes the task, inline, as .NET does. Past 32 nested inlined continuations it is resumed on the pool instead.Task.Yield()always resumes on the pool. There is noSynchronizationContext. - Publishing a frame safely. Before handing its frame to the runtime, a coroutine executes
llvm.coro.save. From that point it counts as suspended, so another thread may resume it even before it reachesllvm.coro.suspend. Without an explicit save, LLVM would place an implicit one just before the suspend, after the frame was already published, and a fast resume on another thread would use a stale resume index. - Blocking.
.Result,.Wait(),GetAwaiter().GetResult()andasync Main(the nativemaincallscsrt_task_waiton the returned task) block on a condition variable. The waiter marks the task (under its lock), and only completing a marked task wakes the waiters: a server’s main thread waits inapp.Run()for its whole life. If a pool worker blocks this way and no other worker is free, another one is started. - Timers. A timer thread hands expired
Task.Delay/CancelAftertimers to the pool, earliest deadline first. Once every 100 ms it also checks for starvation: queued work with no progress and no idle worker. When that happens it injects a worker, up to 512. This is theCountdownEvent/Monitor.Wait-on-pool-threads case, which .NET handles with its starvation detector. - Thread safety. Each task’s state and continuation list are guarded by a per-task spinlock,
held in the former padding word, so the compiler ABI is unchanged. State reads are atomic;
WhenAllcounts down atomically;WhenAnypicks the first completion under the result’s lock. - Cancellation. Callbacks run synchronously inside
Cancel(), most recently registered first. ATask.Delay(ms, token)and a linked source register their own cancellation as one of those callbacks, as in .NET.CancellationToken.Register/UnsafeRegister(every overload) andCancellationTokenRegistrationare corelib C# (corelib/Cancellation.cs): a registration is a callback node in the source’s list, soDispose/Unregisterremove it (andDisposewaits for a callback running on another thread), and the corelib’scsrt_cts_notifyruns the list with .NET’s exception handling:Cancel()runs every callback and throws anAggregateExceptionof what they threw,Cancel(true)lets the first exception through and leaves the rest unrun. A token that is already canceled runs a new callback at once; a disposed source drops it.Dispose,TryReset,CancelAsync,new CancellationToken(bool)and everyCreateLinkedTokenSourceoverload follow .NET (ObjectDisposedExceptionfromCancel/Token/CancelAfteronce disposed; a disposed linked source leaves its parents). Programs that never register a callback keep the C runtime’s own loop. - GC. Work queues, timers and continuation lists are GC arrays rooted by globals. Iterator exceptions are parked in thread-local storage, which the collector also scans.
Supported: await on tasks, value tasks and configured awaitables; Task.FromResult,
CompletedTask, Delay (with tokens), Yield, WhenAll (Task[] and Task<T>[], with the
result as T[], including loose params arguments), WhenAny; Task.Run(Action | Func<T> | Func<Task> | Func<Task<T>>) on the pool, where Func<T> uses a compiler-generated per-T thunk;
.Result, .Wait(), GetAwaiter().GetResult(), IsCompleted/IsFaulted/IsCanceled,
ConfigureAwait (a no-op without a synchronization context); ValueTask<T> constructors and
AsTask(); async lambdas and local functions; async instance methods; async void; faulted and
canceled tasks, AggregateException, TaskCompletionSource, CancellationTokenSource.
Async state machines compiled from IL
Libraries consumed as assemblies (docs/adr/0010-il-frontend.md) contain what the C# compiler made of
their async methods: an IAsyncStateMachine (a struct in Release builds, a class in Debug) whose
MoveNext drives a method builder and awaiters. Those are library types, implemented in the corelib
(corelib/AsyncBuilders.cs, corelib/AsyncIterators.cs) on the same csrt task objects:
- Builders.
AsyncTaskMethodBuilder(<T>),AsyncValueTaskMethodBuilder(<T>), thePoolingvariants andAsyncVoidMethodBuilder.StartrunsMoveNexton the caller’s thread. The firstawaitthat does not complete synchronously creates the builder’s task, then copies the state machine into a heap box (.NET’sAsyncStateMachineBox) whoseMoveNextdelegate is the continuation; the ramp’s stack copy and the box share the task, later awaits reuse the box. A method that completes synchronously never allocates a pending task. TheValueTaskbuilders wrap theTaskones; the generic ones keep a synchronous result inline, so the method returnsnew ValueTask<T>(result), as .NET’s do.PoolingAsyncValueTaskMethodBuilder<T>is .NET’s: a suspending method rents a box per state-machine type (state machine,MoveNextdelegate,ManualResetValueTaskSourceCore<T>) from a one-per-thread cache, then a small shared one, and returnsnew ValueTask<T>(box, version);GetResultresets the box and returns it, so a second await of the sameValueTask<T>throwsInvalidOperationExceptionand the steady state allocates nothing. Source methods with that attribute stay coroutines, but hand their task out through a pooled box of the same kind (ValueTaskAwait<T>.OfPooledTask) for the same one-await semantics. The non-genericPoolingAsyncValueTaskMethodBuilderis not pooled: the non-genericValueTaskis a task pointer without a token, so a reused box could not reject a stale await. - Awaiters.
TaskAwaiter, the non-genericValueTaskAwaiter, theConfigured*task awaiters (IsCompleted,GetResult,OnCompleted,UnsafeOnCompleted) andYieldAwaitable.YieldAwaiterare intrinsics over the task pointer:OnCompleted(action)registers anActioncontinuation (csrt_task_on_completed_action), run inline by the thread that completes the task, or queued to the pool if the task had already completed —TaskAwaiterwithout aSynchronizationContext.ValueTaskAwaiter<T>and its configured awaiter are corelib C# (the structValueTask<T>, above). Custom awaiters work through the builders’ genericAwaitOnCompleted/AwaitUnsafeOnCompleted(constrained calls after monomorphization). - Exceptions.
awaitinsidecatch/finallyrethrows throughExceptionDispatchInfo(corelib; no stack traces, soThrow()rethrows the same object). Asyncvoidexceptions end the process throughcsrt_unhandled_exception, as in the source path. - Async iterators.
AsyncIteratorMethodBuilderandManualResetValueTaskSourceCore<T>(a port of .NET’s, with its execution-context flow and SynchronizationContext / TaskScheduler capture).MoveNextAsync()returnsnew ValueTask<bool>(this, version), which keeps the source (the structValueTask<T>, above). A non-genericValueTaskover anIValueTaskSourceis still bridged to a csrt task, completed at once if the source is, otherwise from the source’sOnCompletedcontinuation (GetResultis called once, after completion).[EnumeratorCancellation]tokens combine throughCancellationTokenSource.CreateLinkedTokenSource.
Cancellation (both paths). An OperationCanceledException escaping an async method cancels its
task (IsCanceled, not IsFaulted) and await rethrows that same exception object, as .NET does;
.Result/.Wait() throw an AggregateException holding a TaskCanceledException
(csrt_task_fault_async).
Iterators
An iterator object is { mt, i32 state, i32 taken, frame, args, clone, reserved, current @ +48 }.
Each element type gets a compiler-emitted method table (ModuleCodeGen.IteratorMethodTable) with
a real interface map:
- sync:
IEnumerable<T>,IEnumerable,IEnumerator<T>,IEnumerator,IDisposable; - async:
IAsyncEnumerable<T>,IAsyncEnumerator<T>,IAsyncDisposable.
Each slot is a small thunk over the runtime, so foreach, await foreach and any code holding
an IEnumerable<T> reach iterators through ordinary interface dispatch.
MoveNext()resumes the frame and returnsstate == 1.Dispose()on a suspended iterator destroys the coroutine. Eachyieldinsidetryhas a destroy edge through the enclosingfinallyblocks, so earlybreak/returnfrom aforeachruns them, as in .NET.GetEnumerator()returns the object itself the first time. After that it calls the per-methodclonethunk, which re-invokes the iterator with the saved arguments, so enumerating the same enumerable twice starts over.- Async iterators: each
MoveNextAsync()returns a fresh pendingValueTask<bool>. The nextyield returncompletes it withtrue, and the end of the body completes it withfalse. Awaits inside the body suspend as in any async method.
Deviations from .NET
- Thread injection. The pool doesn’t do .NET’s hill-climbing. It starts processor-count workers and injects more only when work is starving or a worker blocks on a task.
- Thread identity. Which pool thread runs a continuation may differ from .NET. Programs whose output depends on thread ids or on interleaving are nondeterministic under both runtimes.
- Elision.
CoroElidedoesn’t fire for iterators: the frame handle escapes into the heap iterator object, andMoveNextgoes through the runtime. A future optimization could resume directly when the enumerator’s concrete iterator is statically known. - Non-generic
IEnumerator.Currenton a value-type iterator boxes a primitive or a user struct. Enums are not supported yet. - Not supported: custom awaitables awaited from source (user
GetAwaiterpatterns; IL state machines handle them).SynchronizationContext, customTaskSchedulers,Task.Waittimeouts andTaskCreationOptionsare supported (samples 448, 543, 1020).WithCancellation/ConfigureAwaitonIAsyncEnumerable<T>pass the token toGetAsyncEnumerator(IL and hand-written enumerables); on csharpc’s own (source) async iterators a cancelable token throwsNotSupportedExceptioninstead of being ignored: their[EnumeratorCancellation]parameter is already captured in the coroutine frame.