2y ago · Oct 14, 2023 4:30 PM
Before C# 8, returning multiple items asynchronously required fetching the entire list into memory first ().
With, data streams item-by-item as it arrives:
The attribute ensures the consumer's token propagates into the async generator method properly!
CODE
Task<List<T>>With
CODE
IAsyncEnumerable<T> CSHARP
using System.Runtime.CompilerServices;
public async IAsyncEnumerable<SensorData> StreamSensorReadingsAsync([EnumeratorCancellation] CancellationToken ct = default)
{
while (!ct.IsCancellationRequested)
{
SensorData data = await ReadHardwareSensorAsync(ct);
yield return data; // Streams to consumer immediately!
await Task.Delay(100, ct); // 10Hz tick
}
}
// Consuming with await foreach
await foreach (SensorData reading in StreamSensorReadingsAsync(cancellationToken))
{
Console.WriteLine($"Temperature: {reading.Temp}°C");
}The
CODE
[EnumeratorCancellation] CODE
WithCancellation(ct)
LinQ_Lover · C# Developer
Clean code, fluent LINQ expressions, and expressive C# patte...
Clean code, fluent LINQ expressions, and expressive C# patte...
The following users thanked LinQ_Lover for this post: