IAsyncEnumerable & await foreach
Stream data asynchronously with IAsyncEnumerable, yield in async iterators, and consume with await foreach.
Why IAsyncEnumerable?
IAsyncEnumerable<T> (introduced in C# 8 and .NET Core 3) enables asynchronous streaming — you yield items one at a time as they become available, without loading everything into memory first. Think: reading a database cursor row by row, or streaming API responses.
Writing an Async Iterator
Declare a method returning IAsyncEnumerable<T> and use yield return inside an async method. The await and yield return keywords coexist naturally.
public async IAsyncEnumerable<int> GenerateNumbersAsync(int count)
{
for (int i = 0; i < count; i++)
{
await Task.Delay(100); // simulate async work per item
yield return i;
}
}All lessons in this course
- IAsyncEnumerable & await foreach
- System.Threading.Channels
- ValueTask & Avoiding Allocations
- ConfigureAwait & Synchronization Context