Skip to main content

How to Use IAsyncEnumerable and await foreach in C#

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

Some data arrives a piece at a time: rows from a database, pages from a web API, words from a language model. Instead of waiting for all of it and returning a list, a C# method can hand out each value as soon as it has it, as an IAsyncEnumerable<T>, and the caller reads them with await foreach while they arrive.

Syntax​

A method that produces values over time:

An async iterator
async IAsyncEnumerable<T> MethodName(parameters, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
// await something that takes time...
yield return value;
}

A loop that reads them:

An await foreach loop
await foreach (T item in MethodName(arguments).WithCancellation(token))
{
// use item
}
PartWhat it is
asyncLets the method await, like any async method
IAsyncEnumerable<T>The return type: a sequence of T values that arrive over time
yield return valueHands one value to the caller and pauses the method until the caller asks for the next
await foreach (T item in ...)Reads the values one at a time, waiting for each
[EnumeratorCancellation] CancellationToken (optional)Lets the caller stop the method. Needs using System.Runtime.CompilerServices;
.WithCancellation(token) (optional)How the caller passes that token

Microsoft's C# reference describes the loop: Use the await foreach statement to consume an asynchronous stream of data, that is, a collection type that implements the IAsyncEnumerable<T> interface. Each iteration of the loop can suspend while the next element is retrieved asynchronously.

The Example​

A countdown in a console app: a method that counts down from 5, one number a second, and a loop that prints each number with the time it arrived. The one-second Task.Delay stands in for anything slow that produces values. Every command below was run with the .NET 10 SDK.

Prerequisites​

  • The .NET SDK. dotnet --version should print a version number; this page used 10.0.404.

Step 1: Create a Console App​

Terminal
dotnet new console -o Countdown
cd Countdown
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/Countdown/Countdown.csproj:
Restore succeeded.

Step 2: Write the Iterator and the Loop​

Replace everything in Program.cs:

Program.cs
await foreach (int number in CountdownAsync(5))
{
Console.WriteLine($"{DateTime.Now:HH:mm:ss} {number}");
}

Console.WriteLine($"{DateTime.Now:HH:mm:ss} Liftoff!");

static async IAsyncEnumerable<int> CountdownAsync(int from)
{
for (int i = from; i > 0; i--)
{
await Task.Delay(TimeSpan.FromSeconds(1));
yield return i;
}
}

Program.cs in a macOS-style editor window: an await foreach loop over CountdownAsync(5) that prints each number with the time, a Liftoff! line after the loop, and CountdownAsync, an async IAsyncEnumerable of int that waits a second and yields each number from 5 down to 1

  • CountdownAsync is an async iterator: async, returning IAsyncEnumerable<int>, with yield return inside. Each time round its loop it waits a second, then hands one number to the caller.
  • await foreach asks for the next number, waits until the method yields it, runs the loop body, and asks again. When the method ends, so does the loop.
  • Nothing is collected first. There's no list of numbers anywhere: each one goes from yield return straight into the loop.

Step 3: Run It​

Terminal
dotnet run
Output
05:51:55 5
05:51:56 4
05:51:57 3
05:51:58 2
05:51:59 1
05:51:59 Liftoff!

One number a second: each line printed as soon as its number was ready. A method that built a list and returned it would have printed nothing until all five were ready.

Step 4: Let the Caller Stop It​

A caller that doesn't want every value can cancel. Replace Program.cs with a version that cancels after 2.5 seconds:

Program.cs
using System.Runtime.CompilerServices;

using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(2.5));

try
{
await foreach (int number in CountdownAsync(5).WithCancellation(cancellation.Token))
{
Console.WriteLine($"{DateTime.Now:HH:mm:ss} {number}");
}

Console.WriteLine($"{DateTime.Now:HH:mm:ss} Liftoff!");
}
catch (OperationCanceledException)
{
Console.WriteLine($"{DateTime.Now:HH:mm:ss} Countdown stopped.");
}

static async IAsyncEnumerable<int> CountdownAsync(int from, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
for (int i = from; i > 0; i--)
{
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
yield return i;
}
}
  • CancellationTokenSource(TimeSpan.FromSeconds(2.5)) creates a token that cancels itself after 2.5 seconds.
  • .WithCancellation(cancellation.Token) passes the token to the stream.
  • [EnumeratorCancellation] tells the compiler to deliver that token into the method's cancellationToken parameter. Without it, the token from WithCancellation never reaches the method; the compiler warns CS8425, and cancelling does nothing, as Fixed: CS8425 Async-iterator has one or more parameters of type 'CancellationToken'... shows.
  • Task.Delay(..., cancellationToken) throws OperationCanceledException when the token is cancelled, which ends the loop, and the catch reports it.

Run it again:

Output
05:52:41 5
05:52:42 4
05:52:43 Countdown stopped.

Two numbers, then the countdown stopped at the 2.5-second mark, in the middle of waiting for the third.

Common Mistakes​

MistakeWhat happensDo this instead
foreach without awaitThe code doesn't compile: an IAsyncEnumerable needs await foreachWrite await foreach
A CancellationToken parameter without [EnumeratorCancellation]Warning CS8425, and WithCancellation doesn't cancelAdd the attribute
Collecting everything into a list inside the iteratorThe caller waits for all of it againyield return each value as soon as you have it

Troubleshooting​

SymptomLikely causeFix
Every value prints at the endThe method builds a list and returns it, instead of yieldingUse yield return inside the loop that produces the values
Cancelling does nothingThe token doesn't reach what the method awaitsMark the parameter with [EnumeratorCancellation] and pass it on

FAQ​

When should I use IAsyncEnumerable instead of returning a list?​

When the values arrive over time and the caller can use each one as it comes: showing progress, streaming text to a user, or processing records without holding them all in memory. If the caller needs the whole set before it can do anything, a list is simpler.

Does await foreach clean up the stream when it ends early?​

Yes. Microsoft's tutorial notes that the enumerator is IAsyncDisposable, so the preceding loop will asynchronously dispose the stream when the loop finishes, including when you break out of it or an exception ends it.

Conclusion​

To return values as they become available, write an async method that returns IAsyncEnumerable<T> and yield returns each value, and read it with await foreach. To let callers stop it, take a CancellationToken marked [EnumeratorCancellation] and pass it to whatever the method awaits.

Additional Resources​