Streaming Asynchronous Sequences with `IAsyncEnumerable<T>`
1Concept
`IAsyncEnumerable<T>` combines async/await with `yield return`, allowing servers to stream records (from SQL/gRPC) item-by-item over HTTP WebSockets or SSE without buffering entire tables in memory.
2Architecture Diagram
Database Stream
│
▼ (Reads row 1)
yield return Row 1 ──> Sent over HTTP chunked response immediately to client!
│
▼ (Reads row 2)
yield return Row 2 ──> Sent over HTTP chunked response immediately to client!3Code Example
C# 13 & .NET 9
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
public class AsyncEnumerableDemo
{
public static async IAsyncEnumerable<int> FetchDataStreamAsync([EnumeratorCancellation] CancellationToken ct = default)
{
for (int i = 1; i <= 3; i++)
{
await Task.Delay(10, ct);
yield return i * 100;
}
}
public static async Task Main()
{
await foreach (int item in FetchDataStreamAsync())
{
Console.WriteLine($"Streamed Element: {item}");
}
}
}4Expected Output
Streamed Element: 100 Streamed Element: 200 Streamed Element: 300
5Key Takeaways
- ✓Use `[EnumeratorCancellation]` attribute on CancellationToken parameters in `IAsyncEnumerable`.
- ✓Supported natively in ASP.NET Core Minimal APIs for streaming JSON.
- ✓Eliminates client-side latency by streaming early results immediately.