C# Reference ยท Async and Concurrency
IAsyncEnumerable<T> and await foreach
Reference for IAsyncEnumerable<T> in C#: write async iterators with yield return, consume them with await foreach, cancel them and query them with LINQ.
IAsyncEnumerable<T> is the asynchronous counterpart of IEnumerable<T>. It produces a sequence whose items arrive over time, and moving to the next item is itself an awaitable operation. You write one with an async method that returns IAsyncEnumerable<T> and uses yield return, and you consume it with await foreach.
Use async streams for data that is produced slowly or in pages: rows from a database reader, lines from a network stream, messages from a queue. The consumer processes each item as soon as it arrives instead of waiting for the whole list.
await foreach (var line in ReadLinesAsync()) { Console.WriteLine(line); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public interface IAsyncEnumerable<out T> { IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default); } public interface IAsyncEnumerator<out T> : IAsyncDisposable { T Current { get; } ValueTask<bool> MoveNextAsync(); } static async IAsyncEnumerable<T> Name(...) { ... yield return x; ... yield break; } await foreach (var x in source) { ... } await foreach (var x in source.WithCancellation(token).ConfigureAwait(false)) { ... }
| Part | Description |
|---|---|
GetAsyncEnumerator |
Starts an iteration; await foreach calls it for you. |
MoveNextAsync |
Asynchronously advances; returns false at the end. |
[EnumeratorCancellation] |
Marks the parameter that receives the token passed to WithCancellation. |
yield return / yield break |
Produce an item, or end the sequence. |
Returns: a sequence consumed once. Each GetAsyncEnumerator call restarts the method body.
Errors: exceptions thrown in the iterator surface from MoveNextAsync, i.e. in the await foreach line. An iterator method cannot use ref parameters, and yield return is not allowed inside a try block that has a catch clause.
Usage notes
- Lazy and sequential. The method body runs only while the consumer asks for items. Breaking out of
await foreachcallsDisposeAsync, runningfinallyblocks. - Single consumer. Do not share one enumerator between threads. For several consumers or buffering, use a
Channel<T>. - Cancellation. The token passed to
WithCancellationflows into the[EnumeratorCancellation]parameter. Without that attribute the token passed toWithCancellationnever reaches your code. ConfigureAwaitapplies to the loop too:await foreach (...).ConfigureAwait(false).- Async LINQ. Since .NET 10 the operators (
Where,Select,Take,ToListAsync,CountAsync,FirstAsync, ...) are in the framework inSystem.Linq. Earlier versions needed theSystem.Linq.AsyncNuGet package. Async lambdas are available through the...Awaitor explicit-type overloads. - Not a replacement for
Task<List<T>>. If you always need everything before you can continue, returning a list is simpler. - Prefer small steps. Each
awaitinside the iterator costs a state-machine step; yielding thousands of items per second from a pure CPU source gains nothing overIEnumerable<T>. - Collection expressions and
foreachdo not work on it; you must useawait foreach.