IAsyncEnumerable<T> & Streaming Data
Stream items asynchronously as they become available instead of waiting for an entire collection to be created in memory first.
Part 1: What You Will Learn
Stream items asynchronously as they become available instead of waiting for an entire collection to be created in memory first.
- Return `IAsyncEnumerable<T>` from an async iterator.
- Produce values with `yield return` after asynchronous work.
- Consume the stream with `await foreach`.
- Propagate cancellation with `EnumeratorCancellation` and `WithCancellation()`.
Project setup: Create a .NET 10 Console App. Add `using System.Runtime.CompilerServices;` for EnumeratorCancellation.
Part 2: Topic-Specific Working Example
The following example is written specifically for this lesson. Create the project described above, enter the code, run it, and then change some values to observe how the feature behaves.
using System.Runtime.CompilerServices;
static async IAsyncEnumerable<int> GetSensorReadingsAsync(
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
for (int reading = 1; reading <= 10; reading++)
{
cancellationToken.ThrowIfCancellationRequested();
await Task.Delay(250, cancellationToken);
yield return reading * 5;
}
}
using CancellationTokenSource cts =
new(TimeSpan.FromSeconds(2));
try
{
await foreach (int value in
GetSensorReadingsAsync(cts.Token)
.WithCancellation(cts.Token))
{
Console.WriteLine($"Reading received: {value}");
}
}
catch (OperationCanceledException)
{
Console.WriteLine("Streaming was cancelled.");
}Part 3: How the Code Works
- An async iterator can `await` between produced values and then `yield return` each item.
- The consumer starts processing the first reading without waiting for all ten readings.
- `CancellationToken` allows the caller to stop the stream cleanly.
- Streaming is useful for large result sets, paged APIs, live data, and database queries where materializing everything at once is unnecessary.
Part 4: Mini Project & Practice
Mini project: stream 20 simulated stock-price updates. Stop after five seconds and calculate the running average as each new value arrives.
Tip: Type the code yourself in Visual Studio 2026, run it, then deliberately change one part at a time. The goal is to understand the feature rather than simply copy the finished example.
When you are comfortable with this lesson, continue to Lesson 30.
C# in Visual Studio 2026
📘 This lesson is part of the book C# in Visual Studio 2026 by Dr. Liew Voon Kiong.
View on Amazon Kindle Edition