Write the smallest async IAsyncEnumerable<T> method you can — a loop that awaits something and yields a value — and then open the compiled assembly. The method you wrote is gone. In its place is a nested struct with a name like <Stream>d__0, a dozen fields whose names start with <>, and a single MoveNext that is a flat switch over an integer. That one struct is simultaneously an enumerable, an enumerator, an async state machine, and a hand-rolled task source. Reconstructing your await foreach and yield return out of it is one of the harder things a decompiler does, because the compiler has fused two different suspension mechanisms into one body.
The real question
A plain iterator suspends when the consumer stops pulling. A plain async method suspends when an awaited task is not finished. An async iterator has to do both — yield return and await — inside the same resumable method, and it has to resume into exactly the right place regardless of which kind of suspension it came back from. So where does that unified control flow live after compilation, and how does a reader get from one flat MoveNext back to the two distinct constructs the developer actually wrote?
The answer is a single generated struct that implements four interfaces at once, and a single <>1__state field that multiplexes every suspension point in the method. Read the struct's shape and read that field's dispatch, and the original method falls out.
One method, four interfaces
Here is the source. Nothing exotic — an await and a yield return in a loop, plus a cancellation token so the interesting plumbing shows up:
public static async IAsyncEnumerable<int> ReadBatchesAsync(
string path,
[EnumeratorCancellation] CancellationToken token = default)
{
using var reader = new StreamReader(path);
string? line;
while ((line = await reader.ReadLineAsync(token)) is not null)
{
yield return int.Parse(line);
}
}
The compiler does not emit an iterator and it does not emit an ordinary async method. It emits a struct whose declared interface list is the entire tell:
[CompilerGenerated]
private struct <ReadBatchesAsync>d__0 :
IAsyncEnumerable<int>,
IAsyncEnumerator<int>,
IAsyncStateMachine,
IValueTaskSource<bool>,
IValueTaskSource,
IAsyncDisposable
{
public int <>1__state;
public AsyncIteratorMethodBuilder <>t__builder;
public ManualResetValueTaskSourceCore<bool> <>v__promise;
private bool <>w__disposeMode;
private int <>l__initialThreadId;
private int <>2__current;
private string path;
public string <>3__path;
private CancellationToken token;
public CancellationToken <>3__token;
private CancellationTokenSource <>x__combinedTokens;
private StreamReader <reader>5__2;
private string? <line>5__3;
private ValueTaskAwaiter<string?> <>u__1;
// ... MoveNext, MoveNextAsync, GetAsyncEnumerator, DisposeAsync, etc.
}
No single field proves what this is, but the combination is unambiguous. IAsyncEnumerable<int> + IAsyncEnumerator<int> says stream of items. IAsyncStateMachine + <>t__builder of type AsyncIteratorMethodBuilder says async. IValueTaskSource<bool> + the <>v__promise core says the per-item ValueTask is backed by this struct, not an allocated Task. That full fingerprint is what Glass matches. A plain iterator has the <>2__current but no builder and no promise; a plain async method has the builder but no Current and no enumerator interface. Only the async iterator is all of them at once.
The <>3__-prefixed fields are the parameter-copy slots the enumerable keeps so that each call to GetAsyncEnumerator can hand out a fresh enumerator with the original arguments — that is why the type is both IAsyncEnumerable (the factory) and IAsyncEnumerator (the cursor). The <reader>5__2 and <line>5__3 fields are the hoisted locals: anything whose lifetime must survive a suspension cannot live on the stack, so the compiler lifts it into the struct.
<>1__state multiplexes both kinds of suspension
The field that carries all of the control flow is <>1__state, a single int. It is the resume label, and the critical thing about an async iterator is that it is shared between await suspensions and yield return suspensions. There is no second counter.
Three ranges of values matter. -1 means the enumerator is idle — either not yet started or fully finished. -2 is the sentinel the compiler writes into the field while MoveNext is actively running, so a re-entrant call can tell "executing" from "suspended". Every non-negative value n is a resume point: the body stored n just before it suspended, and the next entry into MoveNext jumps to the instruction immediately after that suspension. An await that has not completed and a yield return that just produced an item both do the same thing — stash a resume number in <>1__state and return — and both are decoded the same way on the way back in.
<>1__state value drives the MoveNext dispatch: −1 is entry, −2 is the running sentinel, and each non-negative case resumes after a specific suspension — whether that suspension was an await or a yield return.
The MoveNextAsync / ValueTask handshake
The consumer never calls MoveNext directly. It calls MoveNextAsync, which returns a ValueTask<bool> — true if an item is ready in Current, false at the end. The elegant part is where that ValueTask comes from. The struct is the task source:
public ValueTask<bool> MoveNextAsync()
{
if (<>1__state == -2) // already disposed
return default;
<>v__promise.Reset();
var self = this;
<>t__builder.MoveNext(ref self); // runs synchronously until first suspension
short version = <>v__promise.Version;
// If MoveNext already finished synchronously, hand back the result;
// otherwise back the ValueTask with this struct as the IValueTaskSource.
return new ValueTask<bool>(this, version);
}
<>v__promise is a ManualResetValueTaskSourceCore<bool>, and because the struct implements IValueTaskSource<bool>, the returned ValueTask<bool>(this, version) is backed by the state machine itself — no Task allocation per item. When MoveNext runs, one of three things happens: it hits an incomplete await and registers the awaiter's continuation to call back in; it reaches a yield return, writes the value to <>2__current, sets <>1__state to the yield resume point, and calls <>v__promise.SetResult(true); or it falls off the end and calls SetResult(false). The awaiter continuation, when the awaited work finishes, re-enters MoveNext through the builder, and the loop continues. That SetResult(true) with a value parked in <>2__current is the runtime signature of a single yield return sitting behind an await.
How Glass maps it back
Glass does not try to "run" this machine. It reads it. The reconstruction is a fixed sequence:
-
Fingerprint the type. A
[CompilerGenerated]nested struct implementingIAsyncEnumerable<T>+IAsyncEnumerator<T>+IAsyncStateMachine+IValueTaskSource<bool>, carrying anAsyncIteratorMethodBuilderand aManualResetValueTaskSourceCore— that is an async iterator and nothing else. The original method is the one whose body was replaced by the builder-start stub that constructs this struct. -
Recover the parameters. The
<>3__-prefixed fields map back to the method's parameters; a<>x__combinedTokensfield plus aCreateLinkedTokenSourcecall inGetAsyncEnumeratormeans the token parameter carried[EnumeratorCancellation], which Glass reattaches. -
Read the dispatch. The
switch (<>1__state)at the top ofMoveNextgives every resume point. Glass classifies each one: a case that resumes right after aGetResulton a<>u__Nawaiter is anawait; a case that resumes right after aSetResult(true)that stored into<>2__currentis ayield return. -
Rebuild the control flow. The hoisted locals (
<reader>5__2,<line>5__3) become ordinary locals; thewhilethat the compiler flattened into gotos between states is folded back into a loop; theusing var readeris recovered from theDisposeAsync/<>w__disposeModecleanup path. What comes out is theReadBatchesAsyncyou wrote, not the struct.
From the CLI the whole thing is one command:
$ glass export ./App.dll --member "M:App.Reader.ReadBatchesAsync(System.String,System.Threading.CancellationToken)"
You get the reconstructed async IAsyncEnumerable<int> with its await and yield return intact and the [EnumeratorCancellation] back on the token. Add --il and Glass shows the honest other side: the <ReadBatchesAsync>d__0 struct, the switch (<>1__state), and the SetResult calls that the C# view hides.
Caveats and where it gets hard
Two honest limits. First, the state-to-construct mapping is only clean when the awaiter and yield patterns match what the current Roslyn emits; hand-written IL, or a struct produced by a different compiler, can suspend in shapes Glass has not fingerprinted, and then the IL view is the truthful fallback — you see the real switch even if the high-level await foreach cannot be named. Second, heavy inlining or optimisation can merge resume points and share hoisted locals across what were logically separate awaits, so the reconstructed loop is faithful to the IL but may not be a character-for-character match to the original source. The <>w__disposeMode path in particular encodes the interaction between await using, early break, and DisposeAsync, and reconstructing the exact placement of a finally there is the subtlest part of the job.
Takeaway
An async iterator is the one place in C# where two different suspension mechanisms are welded into a single resumable method. The compiler expresses it as one generated struct that is enumerable, enumerator, async state machine, and IValueTaskSource all at once, with a single <>1__state field multiplexing every await and every yield return, a <>2__current holding the item, and a ManualResetValueTaskSourceCore so that pulling a stream allocates no per-item Task. Glass.NET reads that fingerprint, decodes the switch (<>1__state) dispatch, classifies each resume point as an await or a yield return, and rebuilds the original await foreach/yield return source — cancellation attribute and all — as pure static analysis, never executing a line. Grab the free build from the Glass.NET download page and open the IL view on the next async IAsyncEnumerable<T> you need to understand.
Top comments (0)