Read the syntax
Use IAsyncEnumerable and await foreach when obtaining the next item can require asynchronous work.
yield return supplies each value to the await foreach consumer.
What it is and why to use it
A Task<List<T>> usually delivers one completed list. An IAsyncEnumerable<T> can deliver items incrementally, with an asynchronous wait between items. This can suit paged or streaming sources. It does not automatically create parallel processing or a background thread; the producer and consumer still define the work and resource lifetime.
How it works
An async iterator returns IAsyncEnumerable<T>, combines await with yield return, and is consumed with await foreach. C# 8 introduced the language support. Cancellation must be connected to and observed by the producer; EnumeratorCancellation supports the token passed through async enumeration. The examples use only in-process yields and a controlled cancellation source.
Common mistakes and limitations
Do not assume an async stream is replayable or that breaking a loop cancels all external work automatically. Dispose enumerators and owned resources correctly, normally through await foreach. Cancellation is cooperative, so token checks and cancellable operations belong inside the producer as appropriate.
Run the examples locally
These complete Program.cs examples use a .NET 10 console project with the C# language version set to 12.0, nullable checking enabled and implicit usings disabled. They use standard .NET libraries and need no extra NuGet packages. This is the verified environment, not a claim that every API requires .NET 10 or works unchanged in .NET Framework, Unity or other runtimes.
Install a supported .NET 10 SDK, create the console project, replace its project file with the settings below, then replace Program.cs with one complete example at a time. Build and run from the project folder. using directives bring namespaces into scope; top-level statements form the program’s entry point, and any helper types follow those statements. Console.WriteLine writes terminal output. Do not combine examples that declare the same type names.
C# in Codectionary’s Playground is editing-only: it does not compile or execute these programs. Run them with the local .NET SDK to reproduce the expected output. Async examples use controlled in-process operations rather than live network services or timing-sensitive delays.
Create and enter a project
dotnet new console -n CSharpExample --framework net10.0
cd CSharpExampleCSharpExample.csproj settings used for these examples
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>12.0</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
</PropertyGroup>
</Project>Build and run after saving one example in Program.cs
dotnet build
dotnet run --no-buildContinue learning
Change one input and predict the result before running it. Follow the related guides to connect this topic with the surrounding language features.
Syntax
await foreach (var item in ReadAsync()) { /* consume item */ }Examples
Yield values incrementally
Consume a small async iterator without a live network dependency.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
await foreach (int value in ReadAsync()) Console.WriteLine(value);
static async IAsyncEnumerable<int> ReadAsync() {
for (int value = 1; value <= 3; value++) {
await Task.Yield();
yield return value;
}
}
- Task.Yield creates an asynchronous scheduling point, not simulated network timing.
- yield return supplies each value to the await foreach consumer.
- The consumer processes values sequentially in the producer’s order; there is no automatic parallel loop.
- Expected output: 1 2 3
- Observe cancellation inside the producer.
Stop a stream cooperatively
Cancel after the first item and handle the resulting cancellation.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.CompilerServices;
using var cancellation = new CancellationTokenSource();
try {
await foreach (int value in ReadAsync().WithCancellation(cancellation.Token)) {
Console.WriteLine(value);
cancellation.Cancel();
}
} catch (OperationCanceledException) { Console.WriteLine("Stopped"); }
static async IAsyncEnumerable<int> ReadAsync([EnumeratorCancellation] CancellationToken token = default) {
for (int value = 1; value <= 3; value++) {
token.ThrowIfCancellationRequested();
await Task.Yield();
yield return value;
}
}
- WithCancellation passes the consumer’s token into enumeration.
- EnumeratorCancellation connects it to the iterator’s token parameter.
- After the first value, cancellation is requested; the next loop check throws and the consumer handles it. No extra values are promised after cancellation.
- Expected output: 1 Stopped
- Observe cancellation inside the producer.
Best practices
- Observe cancellation inside the producer.
- Distinguish incremental asynchronous enumeration from parallel work.
Runtime & versions
.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
C# language reference