C# and .NET • Modern C# baseline
IAsyncEnumerable and Streaming Results
Process asynchronous sequences incrementally with cancellation and bounded memory.
IAsyncEnumerable<T> yields values over time and supports asynchronous iteration. It is useful for paginated APIs, database streams, and long-running producers. Streaming reduces buffering but means consumers may observe partial results before a later failure.
Key points
- Use WithCancellation when the producer supports cancellation.
- Dispose the enumerator when iteration ends early.
Example
static async IAsyncEnumerable<int> ReadValuesAsync(
[System.Runtime.CompilerServices.EnumeratorCancellation]
CancellationToken cancellationToken = default)
{
for (int value = 1; value <= 3; value++)
{
cancellationToken.ThrowIfCancellationRequested();
await Task.Yield();
yield return value;
}
}
What to expect
An await foreach consumer receives values 1, 2, and 3 one at a time.
Practice exercise
Consume the sequence with await foreach and cancel after receiving the first value.
Key idea: Streaming trades all-at-once results for incremental processing and partial completion semantics.