How IAsyncEnumerable<T> combines IEnumerable<T> lazy evaluation with Task asynchronous execution:
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!