In a C# async iterator, when does the method body start running, and what runs when the consumer breaks out of await foreach early?
answer
- calling the method runs nothing yet
- first MoveNextAsync starts the body
- await foreach has a hidden finally
- DisposeAsync resumes pending finally blocks
basics
~20 sCalling an async iterator runs none of its body; it starts at the first MoveNextAsync. When await foreach exits early by break or exception, it awaits DisposeAsync, which runs only the iterator's pending finally blocks and using disposals.
solid answer
~40 sAn async iterator method returns an `IAsyncEnumerable<T>` object without executing its body; the body starts when `await foreach` calls `GetAsyncEnumerator()` and awaits the first `MoveNextAsync()`, and it runs to the next `yield return` or incomplete `await`. `await foreach` wraps the loop in `try`/`finally` and awaits `DisposeAsync()` on the enumerator when the loop ends for any reason, including `break`, `return` or an exception in the body. For a suspended async iterator, `DisposeAsync()` runs the `finally` blocks (and `using` disposals) that enclose the current `yield return`, and those may `await`; the code after that `yield` never runs. Cleanup therefore belongs in `finally` or `using`, not after the loop inside the iterator, and an enumerator obtained by hand and abandoned without `DisposeAsync()` never runs its `finally`.
code
csharp · 27 linesIAsyncEnumerable<int> entries = ReadPagesAsync();
Console.WriteLine("iterator created, body not started yet");
await foreach (int id in entries)
{
Console.WriteLine($"got {id}");
if (id == 2) break; // stop early
}
Console.WriteLine("after loop");
static async IAsyncEnumerable<int> ReadPagesAsync()
{
Console.WriteLine("body starts: opening cursor");
try
{
for (int id = 1; id <= 1000; id++)
{
await Task.Delay(10);
yield return id;
}
}
finally
{
await Task.Delay(10); // await is allowed in finally
Console.WriteLine("finally: cursor closed");
}
}go deeper
Remember that calling an async iterator method does nothing until a loop asks for the first element, and that cleanup belongs in finally or using.
Explain the expansion of await foreach into GetAsyncEnumerator, MoveNextAsync and a finally that awaits DisposeAsync, and what DisposeAsync runs inside a suspended iterator.
Show where early exit bites in production: deferred argument checks, connections closed only in finally, and hand-rolled enumeration that forgets DisposeAsync.
Be ready to set a review rule: every iterator that opens a resource closes it in finally or using, and manual enumerators are always disposed.
## Calling the method runs nothing An async iterator, a method marked `async` that returns `IAsyncEnumerable<T>` and uses `yield return`, is compiled into an object that *describes* the sequence. Calling the method creates that object and returns it; **none of the body runs**, not even the first line. In the example below, "iterator created, body not started yet" prints before the iterator's own first line. The body starts when someone enumerates: 1. `await foreach` calls `GetAsyncEnumerator()` on the sequence, which creates an enumerator. 2. It awaits `MoveNextAsync()`. Now the body runs from the top until it reaches a `yield return` (which completes `MoveNextAsync()` with `true`) or an `await` on something incomplete (which suspends it until the awaited work finishes). 3. Every later `MoveNextAsync()` resumes the body just after the `yield return` where it stopped. One consequence is that argument checks at the top of an async iterator also wait for the first `MoveNextAsync()`. The usual fix, a non-iterator wrapper that validates and then calls a local async iterator, is covered with yield-based methods. ## What await foreach really expands to The loop is shorthand for code like this: ```csharp var e = source.GetAsyncEnumerator(); try { while (await e.MoveNextAsync()) { var item = e.Current; // loop body } } finally { await e.DisposeAsync(); } ``` The `finally` is the important part. Whatever ends the loop, whether the sequence runs out, a `break`, a `return` from the enclosing method or an exception thrown by the loop body, `DisposeAsync()` is awaited on the enumerator. ## What DisposeAsync does to a suspended iterator When the consumer leaves early, the iterator is parked at a `yield return`. Its compiler-generated `DisposeAsync()` does **not** resume the code after that `yield`. It runs only the cleanup that encloses the suspension point: - every `finally` block around the current `yield return`, innermost first; - the `Dispose` or `DisposeAsync` of every `using` or `await using` declaration in scope, since those compile to `finally` blocks too; - any `await` inside those `finally` blocks, which async iterators allow. Code that follows the loop inside the iterator, such as a "closed cursor" log line written after the `for` loop rather than in a `finally`, is skipped. The example below breaks after the second of a thousand entries: the `finally` prints, the remaining 998 fetches never happen. ## The rules that shape cleanup code | Rule | Consequence | |---|---| | `yield return` is not allowed in a `try` that has a `catch` (error CS1626) | wrap individual awaits in `try`/`catch`, or catch at the consumer | | `try`/`finally` around `yield return` is allowed | put cleanup in `finally` so early exit runs it | | `await` inside `finally` is allowed in an async iterator | asynchronous cleanup, such as closing a remote cursor, fits naturally | | `DisposeAsync()` runs only pending cleanup | statements after the loop in the iterator run only on normal completion | ## The manual-enumeration trap The guarantee belongs to `await foreach`, not to the iterator. Code that calls `GetAsyncEnumerator()` and `MoveNextAsync()` by hand owns the cleanup: an enumerator abandoned without `DisposeAsync()` leaves the iterator suspended forever, and its `finally` never runs, not even at garbage collection. A small experiment confirms it: an enumerator advanced once and then dropped prints nothing from its `finally` before the program ends. When enumerating manually, wrap it in `await using`, a subject covered in depth with async disposal, or in your own `try`/`finally`. ## Why interviewers ask This is the question that separates "I have written `await foreach`" from "I know what it compiles to". The expected points are: - the body is lazy and starts at the first `MoveNextAsync()`; - `break` and exceptions both lead to `DisposeAsync()`; - only `finally` and `using` cleanup runs on early exit; - a hand-rolled loop must dispose the enumerator itself. Getting these right is what makes an async iterator that opens connections or cursors safe to hand to callers who stop early. ## When the loop body throws An exception thrown inside the `await foreach` body takes the same path as a `break`. It leaves the loop through the generated `finally`, which awaits `DisposeAsync()`; the iterator's pending `finally` blocks run, and only then does the exception continue to the caller's `catch`. If an iterator `finally` throws in turn, that exception replaces the original one, exactly as nested `finally` blocks behave anywhere else in C#. Keep cleanup code short and unlikely to fail, so it never hides the error that caused the early exit.
- If the loop body throws, does the iterator's finally run before or after the exception reaches the caller's catch?Before. The exception leaves the loop body through the `finally` that `await foreach` generates, which awaits `DisposeAsync()` on the enumerator; that runs the iterator's pending `finally` blocks. Only then does the exception continue to the caller's `catch`. If a `finally` in the iterator throws, its exception replaces the original one, as with any `finally`.
- Why can't you catch exceptions around a yield return in an async iterator, and what do you do instead?The compiler rejects `yield return` inside a `try` that has a `catch` (error CS1626). Put the `try`/`catch` around the awaited call that can fail, store the result in a local, and `yield return` outside the `try`; or let the exception propagate and catch it at the consumer. `try`/`finally` around a `yield return` remains legal.
- Calling an async iterator method starts it running in the background immediately.
- After break, the iterator finishes its loop quietly so the remaining work completes.
- DisposeAsync resumes the iterator after its yield return and runs the rest of the body.
- Async iterators cannot await inside finally, so cleanup must be synchronous.
- An abandoned enumerator's finally block runs when the garbage collector finalizes it.