C# Interview Question #145

What is IAsyncEnumerable<T> in C#?

Advanced Async, Parallelism & Threading Senior Advanced

Quick Interview Answer

IAsyncEnumerable<T> represents an asynchronous stream of values. Instead of waiting for an entire result set before processing begins, values can be produced and consumed asynchronously over time.

Detailed Explanation

IAsyncEnumerable<T> represents an asynchronous stream of values. Instead of waiting for an entire result set before processing begins, values can be produced and consumed asynchronously over time.

It is consumed with await foreach. This is useful for streaming APIs, large result sets, event streams, and data sources where records arrive asynchronously.

Cancellation can also be integrated into asynchronous enumeration.

Code Example

public async IAsyncEnumerable<int> GenerateAsync()
{
    for (int i = 1; i <= 5; i++)
    {
        await Task.Delay(100);
        yield return i;
    }
}

await foreach (int value in GenerateAsync())
{
    Console.WriteLine(value);
}