Developer knowledge network · moderated exchange

Zajednica UnreliableCode

Zajednica za istraživanje, obrnuti inženjering i programiranje programera

Knowledge indexŽivjeti
4Categories
919Threads
2.8KPostovi
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
Datum pridruživanja: Mar 2019
Postovi: 18
Hvala: 40
prije 1 mjeseci · 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
Datum pridruživanja: Jan 2022
Postovi: 10
Hvala: 16
prije 1 mjeseci · 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
Datum pridruživanja: Apr 2018
Postovi: 40
Hvala: 24
prije 1 mjeseci · 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.