Async streams: IAsyncEnumerable and await foreach
suggest changeAn async stream is a sequence whose items arrive over time, where getting each item may need an await: rows from a database, pages from a REST API, lines from a network socket, messages from a queue.
Before C# 8 you had two imperfect choices:
Task<List<T>>waits until everything is loaded before the caller sees the first item, and holds all of it in memory.IEnumerable<T>can hand out items one at a time, but getting the next item can'tawait, so it has to block a thread.
IAsyncEnumerable<T> combines the two: you produce items with yield return inside an async method, and the caller consumes them with await foreach as they become available.
await foreach (Order order in GetOrdersAsync())
{
Console.WriteLine(order.Id);
}
Versions:
- C# 8 / .NET Core 3.0:
IAsyncEnumerable<T>, async iterators,await foreach,IAsyncDisposableandawait using - .NET 6: ASP.NET Core streams
IAsyncEnumerable<T>results without buffering them - .NET 9:
Task.WhenEach - .NET 10: LINQ for async streams (
System.Linq.AsyncEnumerable) is part of the framework
The examples are .NET 10 / C# 14 file-based programs: save the code as app.cs and run it with dotnet run app.cs. All output comes from real runs. If you're new to yield return or async/await, read Iterators, Yield Keyword and Async Await first.
Writing and consuming an async stream
An async iterator is a method that is async, returns IAsyncEnumerable<T> and contains yield return:
using System.Diagnostics;
var sw = Stopwatch.StartNew();
await foreach (int n in CountAsync(3))
{
Console.WriteLine($"{sw.ElapsedMilliseconds / 100 * 100,4} ms: got {n}");
}
Console.WriteLine("done");
static async IAsyncEnumerable<int> CountAsync(int count)
{
for (int i = 1; i <= count; i++)
{
await Task.Delay(300); // pretend to wait for I/O
yield return i;
}
}
300 ms: got 1
600 ms: got 2
900 ms: got 3
The loop body runs as soon as each item is produced. With Task<List<int>> all three lines would print at 900 ms.
Inside the iterator you can mix await and yield return freely, and use loops, using, try/finally and local variables, just like in a regular iterator. yield break ends the stream early.
As with synchronous iterators, the method is lazy: calling CountAsync(3) runs none of its code. The body starts when the caller asks for the first item, and pauses at every yield return until the caller asks for the next one.
What await foreach does
The interfaces are the async twins of IEnumerable<T> and IEnumerator<T>:
public interface IAsyncEnumerable<out T>
{
IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default);
}
public interface IAsyncEnumerator<out T> : IAsyncDisposable
{
T Current { get; }
ValueTask<bool> MoveNextAsync();
}
await foreach is shorthand for the loop below. Here it is written out by hand:
IAsyncEnumerable<int> numbers = CountAsync(2);
IAsyncEnumerator<int> e = numbers.GetAsyncEnumerator();
try
{
while (await e.MoveNextAsync())
{
Console.WriteLine(e.Current);
}
}
finally
{
await e.DisposeAsync();
}
static async IAsyncEnumerable<int> CountAsync(int count)
{
Console.WriteLine("started");
for (int i = 1; i <= count; i++)
{
await Task.Delay(10);
yield return i;
}
Console.WriteLine("finished");
}
started
1
2
finished
Things to notice:
MoveNextAsyncreturnsValueTask<bool>, notTask<bool>. When the next item is already available, as with severalyield returns and noawaitbetween them, getting it allocates nothing.- The enumerator is always disposed with
DisposeAsync, even if the loop body throws. await foreachdoesn't require the interfaces. Likeforeach, it works on any type with a suitableGetAsyncEnumeratormethod, including an extension method. That's howWithCancellationandConfigureAwait(below) work.
await foreach can only be used inside an async method (or in top-level statements). You can't consume an async stream from synchronous code without blocking, and you shouldn't try (see Blocking on async code can cause deadlocks).
A practical example: hiding pagination
APIs usually return large results one page at a time. An async iterator can turn the pages into one flat stream, so callers never deal with cursors:
using System.Runtime.CompilerServices;
// the caller sees one flat stream of orders; paging is hidden
await foreach (Order o in GetAllOrdersAsync().Take(5))
Console.WriteLine($" order {o.Id}");
static async IAsyncEnumerable<Order> GetAllOrdersAsync(
[EnumeratorCancellation] CancellationToken ct = default)
{
string? cursor = null;
do
{
Page page = await FetchPageAsync(cursor, ct);
foreach (Order o in page.Items)
yield return o;
cursor = page.NextCursor;
} while (cursor is not null);
}
// stands in for an HTTP call: 3 orders per page, 10 orders in total
static async Task<Page> FetchPageAsync(string? cursor, CancellationToken ct)
{
int start = cursor is null ? 1 : int.Parse(cursor);
Console.WriteLine($"fetching page starting at {start}");
await Task.Delay(50, ct);
var items = Enumerable.Range(start, Math.Min(3, 11 - start))
.Select(i => new Order(i)).ToList();
int next = start + items.Count;
return new Page(items, next <= 10 ? next.ToString() : null);
}
record Order(int Id);
record Page(List<Order> Items, string? NextCursor);
fetching page starting at 1
order 1
order 2
order 3
fetching page starting at 4
order 4
order 5
The caller wanted 5 orders, so only 2 of the 4 pages were fetched. Pages are requested on demand, and once Take(5) stops asking, the iterator is disposed and no more requests are made. Take on an async stream comes from the .NET 10 LINQ operators, covered below.
Cancellation
Async streams support cancellation through the token parameter of GetAsyncEnumerator. To receive that token in an async iterator, mark a CancellationToken parameter with [EnumeratorCancellation]:
using System.Runtime.CompilerServices;
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(350));
// 1. pass the token as an argument
try
{
await foreach (var tick in TicksAsync(cts.Token))
Console.WriteLine($"a: tick {tick}");
}
catch (OperationCanceledException)
{
Console.WriteLine("a: canceled");
}
// 2. attach the token to someone else's stream with WithCancellation
using var cts2 = new CancellationTokenSource(TimeSpan.FromMilliseconds(250));
IAsyncEnumerable<int> stream = TicksAsync(); // no token here
try
{
await foreach (var tick in stream.WithCancellation(cts2.Token))
Console.WriteLine($"b: tick {tick}");
}
catch (OperationCanceledException)
{
Console.WriteLine("b: canceled");
}
static async IAsyncEnumerable<int> TicksAsync(
[EnumeratorCancellation] CancellationToken ct = default)
{
for (int i = 1; ; i++)
{
await Task.Delay(100, ct);
yield return i;
}
}
a: tick 1
a: tick 2
a: tick 3
a: canceled
b: tick 1
b: tick 2
b: canceled
There are two ways to supply the token:
- As an argument, when you call the iterator yourself:
TicksAsync(cts.Token). - With
WithCancellation(token), when you got anIAsyncEnumerable<T>from somewhere else and can't pass arguments.WithCancellationforwards the token toGetAsyncEnumerator, and[EnumeratorCancellation]makes that token show up in thectparameter.
If you do both, the compiler combines the two tokens, and cancelling either one stops the stream.
Without the attribute, the token passed via WithCancellation is silently ignored. The compiler warns about it:
static async IAsyncEnumerable<int> TicksAsync(CancellationToken ct = default)
{
await Task.Delay(100, ct);
yield return 1;
}
warning CS8425: Async-iterator 'TicksAsync(CancellationToken)' has one or more parameters of type 'CancellationToken' but none of them is decorated with the 'EnumeratorCancellation' attribute, so the cancellation token parameter from the generated 'IAsyncEnumerable<>.GetAsyncEnumerator' will be unconsumed
Treat CS8425 as an error. Cancellation is cooperative: the iterator must pass the token on to whatever it awaits (Task.Delay, HttpClient, a database call) or check ct.ThrowIfCancellationRequested() itself. See Cancellation and timeouts for timeouts and linked tokens.
Early exit, finally and await using
When the consumer leaves the loop early with break, return or an exception, await foreach calls DisposeAsync on the enumerator. That resumes the iterator just long enough to run its finally blocks and dispose its using/await using resources. Then the iterator is finished:
await foreach (string line in ReadLinesAsync())
{
Console.WriteLine($"read: {line}");
if (line == "two") break;
}
Console.WriteLine("after loop");
static async IAsyncEnumerable<string> ReadLinesAsync()
{
await using var reader = new Reader();
try
{
foreach (var s in new[] { "one", "two", "three" })
{
await Task.Yield();
yield return s;
}
}
finally
{
Console.WriteLine("finally runs");
}
}
class Reader : IAsyncDisposable
{
public Reader() => Console.WriteLine("reader opened");
public async ValueTask DisposeAsync()
{
await Task.Delay(10); // e.g. flush and close a network stream
Console.WriteLine("reader closed");
}
}
reader opened
read: one
read: two
finally runs
reader closed
after loop
"three" is never produced, and the cleanup completes before after loop prints. This works the same as try...finally in synchronous iterators (see Try...finally and Early Termination).
IAsyncDisposable came with async streams in C# 8. It's the async twin of IDisposable: DisposeAsync() returns a ValueTask, so cleanup that does I/O (flushing a stream, sending a "close" message, returning a connection to a pool) doesn't block a thread. await using calls it:
await using var conn = await OpenConnectionAsync(); // declaration form
await using (var file = File.OpenWrite(path)) { ... } // block form
Types like FileStream, DbConnection and Utf8JsonWriter implement both interfaces. If a type implements both, prefer await using in async code.
One catch: cleanup only runs if somebody disposes the enumerator. await foreach always does. If you call GetAsyncEnumerator by hand and forget DisposeAsync, the finally blocks never run.
ConfigureAwait
In a library, you usually add ConfigureAwait(false) to every await so the continuation doesn't need the caller's synchronization context (see Disabling synchronization context). Async streams and await using hide some awaits inside the language construct, so there are extension methods to configure them:
using System.Runtime.CompilerServices;
using var cts = new CancellationTokenSource();
await foreach (int n in NumbersAsync().WithCancellation(cts.Token).ConfigureAwait(false))
Console.WriteLine(n);
await using (var res = new Res().ConfigureAwait(false))
{
Console.WriteLine("using resource");
}
static async IAsyncEnumerable<int> NumbersAsync(
[EnumeratorCancellation] CancellationToken ct = default)
{
await Task.Delay(10, ct).ConfigureAwait(false);
yield return 1;
yield return 2;
}
class Res : IAsyncDisposable
{
public ValueTask DisposeAsync()
{
Console.WriteLine("disposed");
return ValueTask.CompletedTask;
}
}
1
2
using resource
disposed
.ConfigureAwait(false)on the stream applies to the hiddenMoveNextAsyncandDisposeAsyncawaits. It returns aConfiguredCancelableAsyncEnumerable<T>, so chainWithCancellationfirst, as above.- Inside the iterator, configure each
awaitas usual. await using (var x = obj.ConfigureAwait(false))gives you a wrapper, not the object itself, so you can't usexto call the object's members. Declare the variable first and wrap it in a separateawait usingif you need both.
Console apps and ASP.NET Core have no synchronization context, so in application code you can skip all of this.
LINQ over async streams (.NET 10)
.NET 10 ships System.Linq.AsyncEnumerable in the framework. It has the full set of LINQ operators for IAsyncEnumerable<T>. Operators that return a sequence (Where, Select, Take, OrderBy...) stay lazy and return another async stream. Operators that return a single value are awaited and have an Async suffix (ToListAsync, CountAsync, FirstOrDefaultAsync, SumAsync...).
IAsyncEnumerable<User> users = GetUsersAsync();
// filtering and projecting, with sync and async lambdas
var names = users
.Where(u => u.Active)
.Select(async (User u, CancellationToken ct) =>
{
await Task.Delay(10, ct); // e.g. look something up
return u.Name.ToUpperInvariant();
});
await foreach (string name in names)
Console.WriteLine(name);
// terminal operators return ValueTask<T>
List<User> all = await users.ToListAsync();
int active = await users.CountAsync(u => u.Active);
User? first = await users.FirstOrDefaultAsync(u => u.Name.StartsWith('c'));
Console.WriteLine($"{all.Count} users, {active} active, first c*: {first?.Name}");
// IEnumerable<T> -> IAsyncEnumerable<T>
int[] ids = [3, 1, 2];
var sorted = await ids.ToAsyncEnumerable().Order().ToArrayAsync();
Console.WriteLine(string.Join(", ", sorted));
static async IAsyncEnumerable<User> GetUsersAsync()
{
string[] names = ["alice", "bob", "carol", "dave"];
for (int i = 0; i < names.Length; i++)
{
await Task.Delay(10);
yield return new User(names[i], Active: i != 1);
}
}
record User(string Name, bool Active);
ALICE
CAROL
DAVE
4 users, 3 active, first c*: carol
1, 2, 3
Things to notice:
- Selector and predicate lambdas can be synchronous, or asynchronous with the signature
async (T item, CancellationToken ct) => .... The async overloads take aValueTaskand pass the stream's cancellation token on to your lambda. - Each terminal operator enumerates the source again. Here
GetUsersAsync()ran four times, once perawait foreachor...Asynccall, the same multiple-enumeration rule as withIEnumerable<T>. If the source is expensive (an HTTP call), materialize it once withToListAsync. - Every terminal operator also takes an optional
CancellationToken.
Before .NET 10 these operators came from the community System.Linq.Async NuGet package. On .NET 10, remove that package reference to avoid ambiguous-call errors between the two implementations. Older target frameworks can use the System.Linq.AsyncEnumerable NuGet package to get the same API as .NET 10.
Don't confuse this with Entity Framework Core's ToListAsync on IQueryable<T>. EF Core translates its queries to SQL, while AsyncEnumerable operators run in memory on items as they arrive.
Streams you get for free
Several framework APIs return IAsyncEnumerable<T>. Consuming one is just an await foreach.
Task.WhenEach: tasks in completion order (.NET 9)
using System.Diagnostics;
var sw = Stopwatch.StartNew();
Task<string>[] tasks =
[
FetchAsync("slow", 600),
FetchAsync("fast", 200),
FetchAsync("medium", 400),
];
await foreach (Task<string> t in Task.WhenEach(tasks))
{
Console.WriteLine($"{sw.ElapsedMilliseconds / 100 * 100,4} ms: {await t}");
}
static async Task<string> FetchAsync(string name, int ms)
{
await Task.Delay(ms);
return name;
}
200 ms: fast
400 ms: medium
600 ms: slow
Task.WhenAll waits for the slowest task. WhenEach lets you process each result as soon as it's ready. It yields the completed Task<T> rather than the value, so await t doesn't wait, and it throws if that task failed. That lets you handle each failure on its own. See Concurrent calls for more on running tasks concurrently.
Channels: producer/consumer
System.Threading.Channels is an async queue. ChannelReader<T>.ReadAllAsync() returns an async stream that ends when the writer calls Complete():
using System.Threading.Channels;
var channel = Channel.CreateBounded<int>(capacity: 2);
Task producer = Task.Run(async () =>
{
for (int i = 1; i <= 5; i++)
{
await channel.Writer.WriteAsync(i); // waits while the channel is full
Console.WriteLine($"wrote {i}");
}
channel.Writer.Complete(); // ends the consumer's await foreach
});
await foreach (int item in channel.Reader.ReadAllAsync())
{
await Task.Delay(50); // slow consumer
Console.WriteLine($" processed {item}");
}
await producer;
wrote 1
wrote 2
wrote 3
processed 1
wrote 4
processed 2
wrote 5
processed 3
processed 4
processed 5
The bounded channel gives you backpressure: once 2 items are waiting, the producer's WriteAsync pauses until the consumer catches up. This is a good way to connect a fast producer to a slow consumer, for example a file reader feeding a database writer.
Others
JsonSerializer.DeserializeAsyncEnumerable<T>(stream)parses the elements of a big JSON array (or JSON Lines) one at a time. See System.Text.Json ("Streams and async").HttpClient.GetFromJsonAsAsyncEnumerable<T>(url)does the same for an HTTP response (example below).- Database clients stream large result sets this way: EF Core's
AsAsyncEnumerable(), the MongoDB driver'sToAsyncEnumerable()on a query, and StackExchange.Redis'sKeysAsyncandHashScanAsync(see Redis).
Streaming from a web API
In ASP.NET Core (.NET 6+), an endpoint that returns IAsyncEnumerable<T> is serialized as a JSON array, and each element is written to the response as it's produced, without first buffering the whole list. On the client, GetFromJsonAsAsyncEnumerable reads the array element by element:
#:sdk Microsoft.NET.Sdk.Web
#:property PublishAot=false
using System.Diagnostics;
using System.Runtime.CompilerServices;
var builder = WebApplication.CreateBuilder();
builder.Logging.ClearProviders();
var app = builder.Build();
app.Urls.Add("http://127.0.0.1:0"); // port 0 = pick any free port
// returning IAsyncEnumerable<T> streams a JSON array
app.MapGet("/prices", (CancellationToken ct) => PricesAsync(ct));
await app.StartAsync();
using var http = new HttpClient { BaseAddress = new Uri(app.Urls.First()) };
var sw = Stopwatch.StartNew();
await foreach (Price? p in http.GetFromJsonAsAsyncEnumerable<Price>("/prices"))
{
Console.WriteLine($"{sw.ElapsedMilliseconds / 100 * 100,4} ms: {p}");
}
await app.StopAsync();
static async IAsyncEnumerable<Price> PricesAsync(
[EnumeratorCancellation] CancellationToken ct)
{
for (int i = 1; i <= 3; i++)
{
await Task.Delay(300, ct);
yield return new Price("ACME", 100 + i);
}
}
record Price(string Symbol, decimal Value);
600 ms: Price { Symbol = ACME, Value = 101 }
900 ms: Price { Symbol = ACME, Value = 102 }
1200 ms: Price { Symbol = ACME, Value = 103 }
The prices arrive about 300 ms apart, while the server is still producing them. The first one takes longer because it includes starting up the first request. The response body on the wire is an ordinary JSON array ([{"symbol":"ACME","value":101},...]), so non-.NET clients can read it as usual, while streaming-aware clients get each element early.
The CancellationToken parameter of the handler is HttpContext.RequestAborted. If the client disconnects, the token is cancelled, and the iterator stops instead of producing data for nobody. For the rest of minimal APIs, see REST APIs.
Rules and pitfalls
Async iterators share the restrictions of both iterators and async methods:
static async IAsyncEnumerable<int> BadAsync()
{
try
{
await Task.Delay(1);
yield return 1;
}
catch (Exception)
{
}
}
static async IAsyncEnumerable<int> Bad2Async(ref int x)
{
await Task.Delay(1);
yield return 1;
}
error CS1626: Cannot yield a value in the body of a try block with a catch clause
error CS1988: Async methods cannot have ref, in or out parameters
error CS1623: Iterators cannot have ref, in or out parameters
yield return is allowed inside try with finally, but not with catch. To handle errors, wrap the code that can fail (the await) in try/catch, store the result in a local variable, and yield return it outside the try block.
Other things to keep in mind:
- Argument validation is deferred. Like a synchronous iterator, an async iterator doesn't run until the first
MoveNextAsync, soArgumentNullException.ThrowIfNull(x)at the top fires only when enumeration starts. If you need eager checks, validate in a non-iterator public method and call a private iterator (see Correctly checking arguments). - Items are produced one at a time. An async iterator doesn't fetch the next item while the consumer processes the current one. If you want the producer to run ahead, put a bounded channel between them.
- Don't enumerate concurrently. One enumerator must not have two
MoveNextAsynccalls in flight.await foreachnever does that. Hand-written code withTask.WhenAlloverMoveNextAsynccan. - Each
await foreachstarts over. An async iterator method re-runs from the top every time it's enumerated, repeating any I/O. - Don't return
IAsyncEnumerable<T>when callers need everything anyway. If the data is small and always consumed in full,Task<List<T>>is simpler and faster. Async streams pay off when the data is large, unbounded, slow to arrive, or often only partly consumed.