0Pricing
C# Academy · Lesson

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

  1. IAsyncEnumerable & await foreach
  2. System.Threading.Channels
  3. ValueTask & Avoiding Allocations
  4. ConfigureAwait & Synchronization Context
← Back to C# Academy