Skip to content

await foreach

Context: await foreach iterates over an IAsyncEnumerable<T> asynchronously, awaiting each element before the loop body executes.

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
public class Example
{
public static async Task Main()
{
await foreach (var item in GetDataAsync())
{
Console.WriteLine(item);
}
}
private static async IAsyncEnumerable<int> GetDataAsync()
{
for (int i = 0; i < 5; i++)
{
await Task.Delay(100);
yield return i;
}
}
}

You can pass a CancellationToken to the GetAsyncEnumerator method.

var cts = new CancellationTokenSource();
await foreach (var item in GetDataAsync().WithCancellation(cts.Token))
{
// ...
}

Processing paginated API responses: Each page is fetched asynchronously, and you await foreach over the pages.

Example: .NET Async Streams documentation