What is IAsyncEnumerable and when would you use it?

C# Async & Concurrency Advanced 3–5 Yrs5+ Yrs Conceptual 1 min read

Quick Answer

IAsyncEnumerable<T> is a sequence you produce and consume asynchronously — await foreach (var x in source). Each item can be fetched with an await, so you can stream results (from a database, a paged API, a file) without buffering the whole set in memory and without blocking a thread between items.

IAsyncEnumerable<T> is an asynchronous sequence — you consume it with await foreach, and each element can involve an await, like fetching the next page from an API or the next batch of rows. The point is streaming: you process items as they arrive without loading everything into memory and without tying up a thread while you wait. EF Core exposes AsAsyncEnumerable for exactly this, and an ASP.NET Core action can return one to stream the response. For a handful of rows I'd just use a list, but for a large or slow feed it's the right tool.

  • Produce with async IAsyncEnumerable<T> GetAsync([EnumeratorCancellation] CancellationToken ct) { ... yield return item; }.
  • EF Core: await foreach (var row in db.Orders.AsAsyncEnumerable()) streams rows instead of ToListAsync().
  • ASP.NET Core can return IAsyncEnumerable<T> from an action and stream the JSON response.
  • Don't overuse it — for small result sets a plain List is simpler; it shines for large or slow streams.