Developer knowledge network · moderated exchange

Społeczność UnreliableCode

Badania programistów, inżynieria wsteczna i społeczność programistów

Knowledge indexNa żywo
4Categories
919Threads
2.8KPosty
Discussion

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

csharp_async_master
Async & Task Expert
MEMBER
Rozpustnik: 57
Data dołączenia: Mar 2019
Posty: 18
Dzięki: 40
1 miesięcy temu · 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
Rozpustnik: 156
Data dołączenia: Jan 2022
Posty: 10
Dzięki: 16
1 miesięcy temu · 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
Rozpustnik: 103
Data dołączenia: Apr 2018
Posty: 40
Dzięki: 24
1 miesięcy temu · 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.