Developer knowledge network · moderated exchange

Сообщество UnreliableCode

Сообщество разработчиков, обратного проектирования и кодирования

Discussion

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

csharp_async_master
Async & Task Expert
MEMBER
Представитель: 57
Дата присоединения: Mar 2019
Сообщения: 18
Спасибо: 40
1 месяцев назад · 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
Представитель: 156
Дата присоединения: Jan 2022
Сообщения: 10
Спасибо: 16
1 месяцев назад · 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
Представитель: 103
Дата присоединения: Apr 2018
Сообщения: 40
Спасибо: 24
1 месяцев назад · 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.