Search for a command to run...

C# gives you two ways to get data back from a method, and each one is missing half of what you need. An async Task<T> can await - it can call a database, wait for a network reply, sleep - but it hands you exactly one value, when it is finished. An IEnumerable<T> hands you as many values as you like, one at a time, lazily - but it cannot await anything: the moment producing the next item needs I/O, the thread blocks. The gap between them is where most real backend work lives: rows arriving from a database, pages arriving from an API, lines arriving from a file. IAsyncEnumerable<T> is the type that closes the gap. It is what you get when the compiler fuses the two state machines it already knows how to build - the iterator's suspend-and-resume and the async method's await - into one.
This post is the next step in the series. The Iterator post built the enumerator by hand, so you could see the state machine. The LINQ post showed that Where and Select are compiler-generated state machines of the same shape. Now the state machine has to suspend for I/O as well as for the next item - and the same pull model, the same deferred execution, and the same boundary rules all still apply, with one new failure mode that is easy to miss.
Take the most ordinary backend job there is: read every order from a paged API and do something with each one. The version everyone writes first collects everything, then processes it:
This works, and it wastes two things: time and memory. Nothing is processed until the last page arrives, so a ten-page sync that could have started working after page one sits idle through nine more round trips. And the whole result set sits in memory at once - for a large export, that is the entire table in a List<T>. The fix is not a faster loop. It is a different return type: instead of returning the finished collection, return the stream and let the caller process each item as it arrives.
The method is async, it returns IAsyncEnumerable<Order>, and it mixes await and yield return freely - that combination is the whole feature. The caller never sees a page, a cursor, or a List<T>. It sees orders, one at a time, and the first one is processed before the second page has even been requested. The memory footprint is one page, not the whole result set, and the wall-clock time is the time of the first page plus processing, not the time of all pages plus processing.
An async iterator behaves exactly like the synchronous iterator from the LINQ post in the one respect people keep forgetting: calling the method runs nothing. An ordinary async Task method starts executing eagerly up to its first suspending await - an async iterator does not run a single line of its body until the first MoveNextAsync(). The method call only builds the state machine and hands it back. And like every iterator, each enumeration is independent: enumerate twice and the body runs twice, which here means two sets of network calls, not two walks over a list.
The variable numbers holds a plan, not a result - the same sentence the LINQ post ended on, now with a network bill attached. If the stream is cheap to rebuild, re-enumeration is harmless. If each item costs a round trip, enumerating twice is two bills and possibly two different answers. The boundary rule from the LINQ post carries over unchanged: materialise at the boundary. Inside a method, a stream is a convenient plan. The moment a result crosses a boundary - returned to a controller, handed to another component, stored for later - it should already be a List<T>, unless the caller genuinely wants to stream and owns the lifetime of whatever the stream reads from.
The two interfaces are the async twins of the ones from the Iterator post, with two differences worth pausing on:
First, MoveNextAsync returns ValueTask<bool>, not Task<bool> - exactly the case ValueTask was designed for: a hot path that usually completes synchronously, where allocating a Task per item would be pure overhead. Second, GetAsyncEnumerator takes a CancellationToken - the synchronous version has nowhere to put one, and this parameter is the hook the next section hangs on. And IAsyncEnumerator<T> derives from IAsyncDisposable, which is what makes cleanup work when you leave the loop early. The await foreach you write is shorthand for this:
That finally is doing real work. Breaking out of an await foreach after the first matching item disposes the enumerator, which runs the iterator's own finally blocks - closing the HTTP response, the file handle, the database reader - at the point where the iterator was suspended, not at some later garbage collection. If your iterator opens a resource, wrap it in a using or a try/finally inside the iterator and trust this mechanism; do not rely on the caller remembering to finish the stream.
The single most common bug with async streams is a silent one, and it is a one-line omission. The consumer cancels through WithCancellation - but that token only reaches the iterator body if the token parameter is marked [EnumeratorCancellation]. Without the attribute, the code compiles, runs, and ignores the cancellation: a cancelled request keeps producing items nobody reads.
Three details complete the picture. The compiler warns (CS8425) when an async iterator has a CancellationToken parameter without the attribute - treat that warning as an error, because the behaviour it describes is a stream that cannot be stopped. If the caller passes a token to the method directly and uses WithCancellation, the two are combined into a linked token, so either side can cancel. And you can mark only one parameter: a second [EnumeratorCancellation] is a compile error (CS8426). The rule is short enough to memorise: every async iterator that takes a token marks it.
The obvious next question - can I Where and Select this? - has an answer that depends on which .NET you target, and it is the one place in this post where the version matters. The synchronous LINQ operators do not work on IAsyncEnumerable<T> at all: chaining .Where(o => o.Total > 100) onto an async stream is a compile error. Before .NET 10, the answer was the System.Linq.Async NuGet package, which provides the same operators - Where, Select, Take, ToListAsync - plus WhereAwait and SelectAwait for the cases where the predicate or projection itself needs to await. Since .NET 10, those operators ship in the base library as System.Linq.AsyncEnumerable, so no package is needed - but a project that still references System.Linq.Async on .NET 10 gets ambiguous-call errors and should drop the reference. The base-library version also drops the Await-suffixed operators: an async lambda is now just Select(async (item, ct) => ...), and the stream's cancellation token is passed into it.
The mechanism behind those operators is worth seeing once, because it is the same shape as everything else in this series - an async iterator wrapping another async stream:
That is all the package is doing for the lazy operators: one async iterator per operator, each pulling from the one before it. The same streaming-versus-buffering rules from the LINQ post apply unchanged - Where and Select stream one item at a time, while OrderBy buffers the whole sequence before yielding anything, which on an async stream means it waits for every network call before producing the first item. And the terminal operators are awaited and suffixed - ToListAsync, CountAsync, FirstOrDefaultAsync - each one enumerates the source again, so the re-enumeration rule from the previous section applies to every one of them.
Two places in a .NET backend make async streams pay for themselves immediately. The first is Entity Framework Core: AsAsyncEnumerable() turns a query into a stream that yields rows as they arrive from the database, instead of buffering all of them, and it composes with the query operators you already write - the filtering still happens in SQL, only the materialisation streams:
The second is ASP.NET Core itself: a controller action can return IAsyncEnumerable<T> directly, and the framework serialises it as a JSON array as the items arrive - the client starts receiving data after the first row instead of after the last one, which is the same win as the paged API example, now on the HTTP boundary. The same idea works on the client side: HttpClient has GetFromJsonAsAsyncEnumerable (in the box from .NET 10; on earlier versions it comes from the System.Net.Http.Json package), which deserialises a JSON array element by element as the bytes arrive, instead of waiting for the whole response body. In all three cases the shape is identical - produce as you go, consume as it arrives, never hold the whole set.
Async streams are a pull model: one consumer asks, one producer answers. Sometimes the producer and the consumer are separate pieces running concurrently - a background job producing work items while a handler consumes them, or several producers feeding one consumer - and a pull loop cannot express that. That is what Channel<T> is for, and its bridge back into this post is one method: ReadAllAsync() returns an IAsyncEnumerable<T>, so everything in this post - await foreach, WithCancellation, early-break disposal - applies to a channel consumer unchanged:
The channel owns the buffering and the backpressure - a bounded channel makes the producer wait when the consumer falls behind, which is the one thing a bare async iterator cannot do for you. The next post in the series goes into channels properly: bounded vs unbounded, backpressure, and the producer/consumer patterns that replace queues of Tasks. For now, the point is the seam: ReadAllAsync turns a concurrent producer into an async stream, and from there the whole model in this post takes over.
Async streams inherit every trap from the LINQ post, and add three of their own:
Re-enumeration re-fetches. An IAsyncEnumerable<T> over a database or an API is a plan to fetch the data again. Enumerate it twice and you paid for two round trips - and the terminal operators (ToListAsync, CountAsync, FirstOrDefaultAsync) each enumerate, so chaining two of them over the same stream runs it twice.
The stream outlives its source. A method returns an IAsyncEnumerable<T> built over a DbContext, the caller enumerates it after the context is disposed, and the exception arrives far from the line that caused it. The LINQ post's boundary rule applies with higher stakes, because the enumeration is a network call, not a loop.
Blocking on an async stream deadlocks or wastes a thread. There is no synchronous way to consume an IAsyncEnumerable<T> - .Result or .GetAwaiter().GetResult() on MoveNextAsync() is the sync-over-async trap, and on a captured context it can deadlock outright. If the caller cannot be async, the stream should have been materialised to a List<T> before it crossed the boundary.
A missing [EnumeratorCancellation] compiles and runs. The stream ignores WithCancellation, the request is cancelled, and the producer keeps fetching pages nobody reads. Treat CS8425 as an error.
Terminal operators defeat streaming. ToListAsync() on a stream you only wanted to forward is the async version of the buffering mistake: it waits for every item before returning anything. Stream it, or materialise it deliberately - never by accident.
Return IAsyncEnumerable<T> when the caller wants items as they arrive. Return Task<List<T>> when the caller wants the whole result. Pick per call site, not per habit.
Materialise at boundaries. Never return a bare IAsyncEnumerable<T> built over a DbContext, a file, or an HTTP response. Return a List<T> - or hand over the stream only when the caller owns the lifetime of what it reads from.
Mark the token. Every async iterator that takes a CancellationToken marks it [EnumeratorCancellation], and every consumer passes one via WithCancellation.
Dispose by breaking. Breaking out of await foreach disposes the enumerator - use it freely for first-match searches, and put resource cleanup in try/finally inside the iterator.
Know which operators buffer. OrderBy over an async stream waits for every item before yielding the first - the same rule as the LINQ post, now priced in network calls.
Use channels when the producer runs on its own. A pull loop cannot express concurrent production; ReadAllAsync() turns a channel back into a stream.
An async method gives you one value. An iterator gives you many values but cannot wait. IAsyncEnumerable<T> is the two state machines fused: the pull model from the Iterator post, finally allowed to await - and every rule from the LINQ post still applies, now priced in network calls.
The next post in the series takes the seam this one ended on - Channel<T> - and goes into it properly: bounded vs unbounded channels, backpressure, and the producer/consumer patterns that replace queues of Tasks.
An async method gives you one value; an iterator gives you many but cannot wait. IAsyncEnumerable<T> fuses the two state machines: the pull model from the Iterator post, finally allowed to await - with deferred execution, cancellation, and the same boundary rules, now priced in network calls.
A list of orders in memory, rows streaming out of a database, pages from an API - from the consumer's side they are the same question: give me the next item, and tell me when there are no more. The Iterator pattern is that question answered as an interface pair, and in .NET it is the shape of foreach and LINQ themselves: hand-built enumerators, yield return, deferred execution, and the async twin IAsyncEnumerable<T> - including the costs, and when a List is the honest answer.
An order is placed, and five parts of the system need to know. The Observer pattern flips who knows about whom: the publisher announces one fact, subscribers come and go, and the publisher never changes. From hand-built subjects to C# events, IObservable<T>, and MediatR notifications - with the push and pull models demonstrated in code - including the costs, and when a direct call is the honest answer.