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; } }}Cancellation
Section titled “Cancellation”You can pass a CancellationToken to the GetAsyncEnumerator method.
var cts = new CancellationTokenSource();await foreach (var item in GetDataAsync().WithCancellation(cts.Token)){ // ...}Real-world usage example
Section titled “Real-world usage example”Processing paginated API responses: Each page is fetched asynchronously, and you await foreach over the pages.
Example: .NET Async Streams documentation