Skip to content

IAsyncEnumerable<T>

Context: IAsyncEnumerable<T> is the asynchronous version of IEnumerable<T>. It allows asynchronous iteration with await foreach.

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
public class FileReader
{
public async IAsyncEnumerable<string> ReadLinesAsync(string filePath)
{
using var reader = new StreamReader(filePath);
string line;
while ((line = await reader.ReadLineAsync()) != null)
{
yield return line;
}
}
}
  • No need to buffer all data in memory.
  • Each element can be produced asynchronously.
  • Works with await foreach.

Database streaming: In EF Core, AsAsyncEnumerable() returns IAsyncEnumerable<T> for streaming query results.

Example: EF Core async streaming