Async streams
Async streams
An asynchronous stream exposes items over time through IAsyncEnumerable<T>. Unlike Task<List<T>>, a consumer can process each available item before the entire sequence is collected. The consumer uses await foreach; each advance can suspend independently.
Examples target the proposed C# 14 / .NET 10 console baseline (one independent Program.cs per example, nullable enabled). Expected outputs are reasoned, not executed. Source-generation examples require the standard SDK and its built-in generators; no extra packages or external services are used.
Consume a finite stream
An async iterator combines await with yield return. The following in-memory source intentionally uses completed tasks to demonstrate the contract without scheduling assumptions.
using System;using System.Collections.Generic;using System.Threading.Tasks;await foreach (int units in Updates()) Console.WriteLine(units);static async IAsyncEnumerable<int> Updates(){ foreach (int value in new[] { 4, 7, 2 }) yield return await Task.FromResult(value);}The consumer requests the next item only after the current loop body completes. This pull pattern limits demand, but a real producer might buffer independently.
Expected output (reasoned, not executed):
472Stop enumeration early
Breaking out of await foreach disposes its async enumerator. A finally block in the iterator is useful for releasing resources, even when not all items are read.
using System;using System.Collections.Generic;using System.Threading.Tasks;await foreach (string message in Messages()){ Console.WriteLine(message); break;}static async IAsyncEnumerable<string> Messages(){ try { yield return await Task.FromResult("first"); yield return "second"; } finally { Console.WriteLine("closed"); }}The second yield is not reached; enumeration cleanup runs before control leaves the loop.
Expected output (reasoned, not executed):
firstclosedPropagate cancellation
WithCancellation passes a token to the enumerator. EnumeratorCancellation connects that token to the iterator parameter; the iterator still has to observe cancellation.
using System;using System.Collections.Generic;using System.Runtime.CompilerServices;using System.Threading;using System.Threading.Tasks;using var stop = new CancellationTokenSource();try{ await foreach (int item in Read().WithCancellation(stop.Token)) { Console.WriteLine(item); stop.Cancel(); }}catch (OperationCanceledException) { Console.WriteLine("canceled"); }static async IAsyncEnumerable<int> Read( [EnumeratorCancellation] CancellationToken token = default){ for (int i = 1; i <= 3; i++) { token.ThrowIfCancellationRequested(); yield return await Task.FromResult(i); }}Cancellation is checked before producing the second item. No timer or external I/O is needed.
Expected output (reasoned, not executed):
1canceledCommon mistakes and edge cases
Do not assume asynchronous iteration means parallel processing or zero buffering. Avoid collecting an unbounded stream into a list. A producer must observe cancellation and own its cleanup; consumers should handle failures and avoid concurrent MoveNextAsync calls on the same enumerator.
Practice and recap
Change the cancellation example so it cancels after item 2. Predict the output and explain why item 3 is absent.
Hint: Cancel only when item equals 2.
Learning objective: Consume finite asynchronous results. See accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Async streams — knowledge check
Apply the lesson concepts to the following scenarios.
What does IAsyncEnumerable<int> expose?
What happens to Messages when the loop breaks?
What does WithCancellation do?
What connects the consumer token to the iterator parameter?
Why avoid materializing an unbounded stream?