Developer knowledge network ยท moderated exchange

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Knowledge indexLive
4Categories
919Threads
2.8KPosts
Discussion

Streaming real-time data asynchronously with IAsyncEnumerable<T> and yield return in C# [StackOverflow Architecture Guide]

csharp_async_master
Async & Task Expert
MEMBER
Rep: 57
Join Date: Mar 2019
Posts: 18
Thanks: 40
1 months ago ยท Jul 1, 2026 2:32 AM
#1

How IAsyncEnumerable<T> combines IEnumerable<T> lazy evaluation with Task asynchronous execution:

CSHARP
public async IAsyncEnumerable<SensorReading> StreamReadingsAsync([EnumeratorCancellation] CancellationToken ct = default)
{
    while (!ct.IsCancellationRequested)
    {
        SensorReading reading = await _sensorClient.ReadNextAsync(ct);
        yield return reading; // Yields item as soon as it arrives!
    }
}

// Consumer
await foreach (var reading in StreamReadingsAsync(cancellationToken))
{
    ProcessReading(reading);
}

Allows consuming high-volume telemetry, database cursors, or WebSocket packets chunk-by-chunk without loading entire datasets into RAM!

channel_concurrency
Reactive & Pipeline
MEMBER
Rep: 156
Join Date: Jan 2022
Posts: 10
Thanks: 16
1 months ago ยท Jul 1, 2026 5:30 AM
#2

Always add [EnumeratorCancellation] to the CancellationToken parameter so .WithCancellation(ct) on the consumer side passes tokens to the enumerator correctly.

dotnet_runtime_architect
.NET Core Specialist
MEMBER
Rep: 103
Join Date: Apr 2018
Posts: 40
Thanks: 24
1 months ago ยท Jul 1, 2026 7:30 PM
#3

Entity Framework Core's .AsAsyncEnumerable() streams millions of database rows directly to HTTP responses with near-zero memory footprint.