AsAsyncEnumerable Extension
02/01/2026
This post explores a template implementation of method that converts an IEnumerable<T> to IAsyncEnumerable<T>. IAsyncEnumerable has been introduced to provide asynchronous iteration over values. The following implementation takes a synchronous enumerable and converts it to asynchronous, allowing the execution of async code in-between each iteration of the source. One could achieve similar results by using a regular foreach loop with an await-ed method in the loop body. However, one might want to create an extension method over for simplified syntax as shown below.
This sample extension method and type contains no 'real' async method invocation, but a developer can easily extend it with a tailored async method call or a delegate (Func<T,Task>) invocation. A good place for such a call would be in the body of MoveNextAsync method. This type as-is only useful for converting sync enumerable to async for example, for mocking purposes in unit tests.
Design decisions for the following type follow the design of the built-in Iterator of .NET class library.
The source argument is validated without the need of iterating the
AsyncEnumerable<T>instance.The iterator does not cancel iteration itself, based on co-operative cancellation it could (should) pass the cancellation token async method invoked.
The enumerable and the enumerator are implemented by the same type.
The state of the enumerator is captured by the _state variable.
The iterator is not thread-safe.
The inner iterator is initialized lazily.
The
Currentproperty returnsdefaultin non-iterating states, which may be null.