In C#, how do you write a method that produces items asynchronously one at a time, and how does a caller loop over them?
answer
- async plus yield return
- a different return type than Task
- IAsyncEnumerable<T> in, await foreach out
- MoveNextAsync awaited per element
basics
~20 sMark the method async, return IAsyncEnumerable<T>, and use await and yield return in its body. The caller consumes it with await foreach, which awaits each element and runs the loop body as soon as that element is yielded.
solid answer
~40 sA method marked `async` that returns `IAsyncEnumerable<T>` and contains `yield return` is an **async iterator**: it may `await` between yields, for example to fetch the next page from a remote log API, and it hands out each entry as soon as it has one. The caller writes `await foreach (var entry in TailAsync())`; every iteration awaits the enumerator's `MoveNextAsync()`, so the loop body runs per element instead of after the whole sequence exists. The compiler enforces both sides: an iterator returning `IAsyncEnumerable<T>` without `async` is error CS8403, and a plain `foreach` over an `IAsyncEnumerable<T>` is error CS8414, whose message asks whether you meant `await foreach`. The feature dates from C# 8 and .NET Core 3.0, so every supported release has it.
code
csharp · 28 linesusing System.Diagnostics;
var sw = Stopwatch.StartNew();
await foreach (LogEntry entry in TailAsync(pages: 3))
{
Console.WriteLine($"{sw.ElapsedMilliseconds,4} ms {entry.Level} {entry.Message}");
}
static async IAsyncEnumerable<LogEntry> TailAsync(int pages)
{
for (int page = 1; page <= pages; page++)
{
string[] lines = await FetchPageAsync(page); // simulated remote call
foreach (string line in lines)
{
string[] parts = line.Split(' ', 2);
yield return new LogEntry(parts[0], parts[1]);
}
}
}
static async Task<string[]> FetchPageAsync(int page)
{
await Task.Delay(300);
return [$"INFO page {page} started", $"WARN page {page} slow"];
}
record LogEntry(string Level, string Message);go deeper
Recall the three ingredients of an async iterator: the async modifier, an IAsyncEnumerable<T> return type and yield return, plus await foreach on the calling side.
Explain what await foreach does each iteration: it awaits MoveNextAsync, reads Current, and awaits DisposeAsync when the loop ends, which is why the body runs per element.
Show you can read the compiler's errors for the common mix-ups, such as CS8403 and CS8414, and say when a blocking bridge like ToBlockingEnumerable is acceptable.
Be ready to judge where an asynchronous sequence belongs in a public API surface and where a buffered result is the simpler contract for callers.
## What an async iterator is C# has had two separate tools for a long time: **iterators**, methods that use `yield return` to hand out a sequence one element at a time, and **async methods**, methods marked `async` that can `await` an operation without blocking a thread. Since C# 8 (with .NET Core 3.0 supplying the interfaces), the two combine into an **async iterator**: a method that awaits *and* yields. The return type is what tells the compiler which kind of method it is looking at: - `IEnumerable<T>` with `yield return` is an ordinary synchronous iterator; - `Task<T>` with `async` is an ordinary async method that produces one result; - `IAsyncEnumerable<T>` (or `IAsyncEnumerator<T>`) with `async` and `yield return` is an async iterator that produces many results over time. ## Writing one A log-tailing client that reads a paged remote API is the classic shape. Each page needs a network call, and each page holds several entries: ```csharp static async IAsyncEnumerable<LogEntry> TailAsync(int pages) { for (int page = 1; page <= pages; page++) { string[] lines = await FetchPageAsync(page); foreach (string line in lines) yield return Parse(line); } } ``` The rules the compiler enforces are few: 1. The method must carry the `async` modifier. Without it, `yield return` in a method returning `IAsyncEnumerable<T>` is **error CS8403**: "Method 'Numbers()' with an iterator block must be 'async' to return 'IAsyncEnumerable<int>'". 2. The body needs at least one `yield` statement; `await` is allowed anywhere an ordinary async method allows it. 3. A `yield return` cannot sit inside a `try` block that has a `catch` clause (**error CS1626**), the same restriction synchronous iterators have. 4. You never `return` a collection; the sequence *is* the series of `yield return` statements. ## Consuming it with await foreach The consumer side is a loop with one extra keyword: ```csharp await foreach (LogEntry entry in TailAsync(pages: 3)) Console.WriteLine(entry); ``` Under the hood the loop asks the sequence for an `IAsyncEnumerator<T>` through `GetAsyncEnumerator()`, then repeatedly awaits `MoveNextAsync()`, which returns a `ValueTask<bool>`, and reads `Current` while the result is `true`. When the loop ends, it awaits `DisposeAsync()` on the enumerator. Because each `MoveNextAsync()` completes as soon as the iterator reaches its next `yield return`, the loop body runs per element: in the example below, the first two entries print after about 300 ms, not after the 900 ms that all three pages take. The method containing the `await foreach` must itself be able to await, so it is an `async` method or top-level code. ## What the compiler checks | Mistake | Diagnostic | |---|---| | Iterator returns `IAsyncEnumerable<T>` but lacks `async` | error CS8403 | | Plain `foreach` over an `IAsyncEnumerable<T>` | error CS8414, suggesting `await foreach` | | `await foreach` over a `List<T>` | error CS8415, suggesting plain `foreach` | | `await` applied to the sequence itself | error CS9353, suggesting `await foreach` | | `yield return` inside `try` with a `catch` | error CS1626 | The messages for CS8414, CS8415 and CS9353 name the fix, which makes the mix-up hard to ship. ## How it compares with its neighbours | Return type | Results | When the caller sees the first one | |---|---|---| | `Task<List<T>>` | many, delivered together | after the last one is ready | | `IEnumerable<T>` iterator | many, one at a time | immediately, but each step blocks the thread while it waits | | `IAsyncEnumerable<T>` iterator | many, one at a time | as soon as it is yielded, without blocking a thread | The asynchronous sequence is the only one of the three that both streams and releases the thread while it waits for the next page. ## Slips that show up in code review - An iterator that awaits nothing still compiles as an async iterator, but if every element is already in memory, an `IEnumerable<T>` or a plain list says so more honestly. - A method that builds a `List<T>` and then yields from it has buffered everything first; the signature promises streaming that the body does not deliver. - A caller that awaits the sequence, or loops it with plain `foreach`, gets one of the errors in the table above rather than a quiet bug. Whether streaming is the right design for a given API, cancelling the loop and cleanup on an early `break` are separate questions with their own answers; the core skill here is recognising the three ingredients (`async`, `IAsyncEnumerable<T>`, `yield return`) and the matching `await foreach` on the other side.
- Can await foreach loop over a type that does not implement IAsyncEnumerable<T>?Yes. Like `foreach`, `await foreach` is pattern-based: the type needs a public parameterless `GetAsyncEnumerator` method, which may be an extension method, returning something with a public `Current` property and a parameterless `MoveNextAsync` whose result can be awaited to a `bool`. The interface is only the most common way to satisfy that pattern.
- How do you consume an IAsyncEnumerable<T> from synchronous code that cannot await?`TaskAsyncEnumerableExtensions.ToBlockingEnumerable()` wraps it as an `IEnumerable<T>` that blocks the calling thread on each `MoveNextAsync`. It works in a console tool, but it gives up the point of the async sequence and carries the usual sync-over-async risks on a thread with a single-threaded context, so it is a last resort rather than a bridge to use by habit.
- A plain foreach can loop over IAsyncEnumerable<T> and awaits each item itself.
- To use await and yield return together, the method must return Task<IEnumerable<T>>.
- await foreach collects the whole sequence first, then runs the loop body.
- The async modifier is optional on a method that returns IAsyncEnumerable<T>.
- An async iterator builds a list internally and returns it at the end.