Developer knowledge network · moderated exchange

مجتمع الكود غير الموثوق به

أبحاث المطورين، مجتمع الهندسة العكسية والترميز

Knowledge indexيعيش
4Categories
919Threads
2.8Kدعامات
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 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
مندوب: 156
تاريخ الانضمام: Jan 2022
دعامات: 10
شكرًا: 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
مندوب: 103
تاريخ الانضمام: Apr 2018
دعامات: 40
شكرًا: 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.