Skip to content

2.17 — IAsyncEnumerable and await foreach

← Roadmap · Section: 2. Collections, LINQ and Async Prev: 2.16 Async exceptions · Next: 2.18 Thread safety

Markers: ⭐ · Confidence: 🔴 · Last reviewed: —


TL;DR

  • IAsyncEnumerable<T> is IEnumerable<T> where getting the next item is itself awaitable.
  • It solves a real gap: Task<List<T>> gives you everything at once, and IEnumerable<T> cannot await. Async streams give you items one at a time, as they arrive.
  • Consume it with await foreach. Pass cancellation with [EnumeratorCancellation].

The concept

Before C# 8 there were two options for returning a sequence from an async method, and both had a flaw:

Task<List<Order>> GetOrdersAsync();   // must build the WHOLE list before returning
IEnumerable<Order> GetOrders();       // streams one at a time, but cannot await

The first loses streaming — a million rows means a million objects in memory before the caller sees one. The second cannot do async I/O, so it blocks a thread on every read.

IAsyncEnumerable<T> gives you both: stream one item at a time, and await between items.

A picture: a conveyor belt from a warehouse rather than a delivery van. The van (Task<List<T>>) turns up once with everything, and you wait for the whole load. The belt delivers items as they are picked, you start working on the first one immediately, and you can stop the belt whenever you have enough.


How it works

Producing one

Same as a normal iterator (2.4), but async with IAsyncEnumerable<T>:

public async IAsyncEnumerable<Order> StreamOrdersAsync(
    [EnumeratorCancellation] CancellationToken ct = default)
{
    await using var connection = new SqlConnection(_connectionString);
    await connection.OpenAsync(ct);

    await using var command = new SqlCommand("SELECT * FROM Orders", connection);
    await using var reader = await command.ExecuteReaderAsync(ct);

    while (await reader.ReadAsync(ct))          // await INSIDE the iterator
    {
        yield return new Order
        {
            Id    = reader.GetGuid(0),
            Total = reader.GetDecimal(1)
        };
    }
}

Note there is no return type of Task — it is async IAsyncEnumerable<T>, and you still use yield return. The compiler builds an async state machine that also implements IAsyncEnumerator<T>.

Consuming one

await foreach (var order in StreamOrdersAsync(ct))
{
    Console.WriteLine(order.Total);
}

await foreach calls MoveNextAsync() — which returns a ValueTask<bool> — and awaits it before each item.

[EnumeratorCancellation] — the bit people get wrong

Look again at that parameter attribute. Without it, cancellation silently does nothing.

The problem: await foreach can supply its own token via WithCancellation(...), and the method also has a ct parameter. Which one wins?

// The consumer supplies a token here
await foreach (var o in StreamOrdersAsync().WithCancellation(ct))

[EnumeratorCancellation] tells the compiler "wire the token from WithCancellation into this parameter". Without the attribute, ct stays at its default value of None and cancellation is ignored entirely — with no warning.

So the two ways to cancel are:

// Pass it directly as an argument
await foreach (var o in StreamOrdersAsync(ct)) { }

// Or via WithCancellation — needs [EnumeratorCancellation] to work
await foreach (var o in StreamOrdersAsync().WithCancellation(ct)) { }

Always add the attribute. It costs nothing and makes both forms work.

LINQ over async streams

The standard LINQ operators do not work on IAsyncEnumerable<T> — they are built for IEnumerable<T>. You need the System.Linq.Async NuGet package:

var expensive = await StreamOrdersAsync(ct)
    .Where(o => o.Total > 1000)
    .Take(10)
    .ToListAsync(ct);

.NET 10 began bringing some of these into the base library, but for now the package is the usual answer.


Where it earns its place in ASP.NET Core

Streaming a large API response

[HttpGet("orders/stream")]
public async IAsyncEnumerable<OrderDto> Stream(
    [EnumeratorCancellation] CancellationToken ct)
{
    await foreach (var order in _repo.StreamAllAsync(ct))
        yield return _mapper.ToDto(order);
}

ASP.NET Core understands IAsyncEnumerable<T> return types natively. It serialises items to the response as they are produced, so:

  • Memory stays flat regardless of how many rows there are.
  • The client starts receiving data almost immediately rather than after the full query.
  • If the client disconnects, ct fires and the query stops.

Compare with returning Task<List<OrderDto>> for a million rows: a million DTOs in memory, one enormous JSON string built in memory, and nothing sent until it is all ready.

EF Core

AsAsyncEnumerable() streams rows instead of buffering them:

await foreach (var order in _db.Orders.AsAsyncEnumerable().WithCancellation(ct))
{
    await ProcessAsync(order, ct);
}

⚠️ The database connection stays open for the whole loop. If processing each item is slow, you are holding a connection from the pool for a long time. For heavy per-item work, read in batches instead:

const int BatchSize = 500;
var skip = 0;

while (true)
{
    var batch = await _db.Orders.OrderBy(o => o.Id)
        .Skip(skip).Take(BatchSize).ToListAsync(ct);

    if (batch.Count == 0) break;

    foreach (var order in batch)
        await ProcessAsync(order, ct);      // connection already released

    skip += BatchSize;
}

Code

Reading a huge file line by line without loading it, and without blocking:

public async IAsyncEnumerable<LogEntry> ParseLogAsync(
    string path,
    [EnumeratorCancellation] CancellationToken ct = default)
{
    using var reader = new StreamReader(path);

    while (await reader.ReadLineAsync(ct) is { } line)     // pattern match: not null
    {
        if (TryParse(line, out var entry))
            yield return entry;
    }
}

Used with early exit:

await foreach (var entry in ParseLogAsync("huge.log", ct))
{
    if (entry.Level == LogLevel.Error)
    {
        _logger.LogWarning("First error at {Time}", entry.Timestamp);
        break;               // stops reading — the file reader is disposed properly
    }
}

A 10 GB file where the first error is on line 40 reads 40 lines. Memory stays at one line. And because break disposes the enumerator, the using inside the iterator runs and the file handle closes.


Interview questions

Q: What is IAsyncEnumerable<T> and what problem does it solve?

It is a sequence where fetching each item is itself asynchronous. Before it existed you had to choose between Task<List<T>>, which forces you to build the entire collection before returning anything, and IEnumerable<T>, which streams but cannot await — so any I/O inside it blocks a thread. Async streams give you both: items are produced one at a time as they become available, and the producer can await between them. You consume it with await foreach.

Q: What does [EnumeratorCancellation] do?

It connects the token supplied by the consumer through WithCancellation to the CancellationToken parameter of your iterator method. Without the attribute, that parameter just keeps its default value of CancellationToken.None, so cancellation silently does nothing — the compiler has no way to know which parameter should receive the consumer's token. It is easy to miss because there is no error, just cancellation that quietly fails to work.

Q: When would you use it in ASP.NET Core?

Mainly for streaming large responses. ASP.NET Core supports returning IAsyncEnumerable<T> directly from an action and serialises items as they are produced, so memory stays flat and the client starts receiving data immediately rather than after the whole result set is built. For a query returning hundreds of thousands of rows that is the difference between a predictable memory profile and an out-of-memory exception. It is also useful for background processing pipelines where you want to start work on early items while later ones are still being fetched.

Q: What is the catch with AsAsyncEnumerable in EF Core?

The database connection stays open for the entire duration of the loop, because rows are being streamed as you consume them. If the work you do per item is slow, you are holding a pooled connection for a long time, and under load that can exhaust the pool. For lightweight per-item work it is fine; for anything heavy I would read in batches with Skip and Take instead, so the connection is released between batches.


Traps ⚠️

  • Forgetting [EnumeratorCancellation] means cancellation silently does nothing.
  • Standard LINQ does not work on IAsyncEnumerable<T>. You need the System.Linq.Async package.
  • AsAsyncEnumerable holds a database connection for the whole loop. Batch instead if per-item work is slow.
  • You cannot use await foreach in a non-async method. The whole call chain must be async.
  • Enumerating twice runs the source twice, exactly as with IEnumerable. See 2.6.
  • Returning IAsyncEnumerable<T> from a controller means you cannot easily set a status code partway through — the response has already started once the first item is written.
  • Exceptions thrown mid-stream in a controller action arrive after headers are sent, so the client gets a truncated response rather than a clean error.


Sources