What is the IAsyncEnumerable interface and how is it used?

Answer

IAsyncEnumerable<T> (C# 8+) is the async counterpart to IEnumerable<T> — represents an asynchronous stream that yields items one at a time without loading everything into memory. Producer (generator method): public async IAsyncEnumerable<User> GetUsersAsync([EnumeratorCancellation] CancellationToken ct = default) { var page = 1; while (true) { var users = await FetchPageAsync(page++, ct); if (!users.Any()) yield break; foreach (var u in users) yield return u; } }. Consumer: await foreach (var user in GetUsersAsync(cancellationToken)) { await ProcessAsync(user); }. Benefits: (1) Streaming — process items as they arrive, not all at once. (2) Low memory — no need to buffer the entire result set. (3) Backpressure — naturally flows control. (4) EF Core 3+: await foreach (var u in context.Users.AsAsyncEnumerable()) — stream DB results without loading all rows. Use in ASP.NET Core for streaming API responses. Avoid ToListAsync() when you can stream.