IAsyncEnumerable WithCancellation
08/16/2025
I recently used IAsyncEnumerable
in C# the first time. In this post, I will summarize some of my learnings based on .NET 9.
There is an excellent introduction to Iterating with Async Enumerables that introduces they key concepts from the iterators point of view and then details the internals of an async enumerator.
Key Concepts
IAsyncEnumerable<T>
allows creating iterators that produce elements in an asynchronous fashion. Although it has been around for a few years, it is not commonly seen in application source code. Typically, iteration happens over a collection where elements are already computed, making synchronous iteration adequate, like iterating a list of integers. There are also cases where the elements of an iterator can computed synchronously, for example the runtime provides Enumerble.Range or Enumerable.Repeat iterators. Additionally, Select extension can project each element of a sequence into a new shape, like a Task<T>
, then a consumer awaits these tasks to complete concurrently.