Asynchronous streams
Context: Asynchronous streams (C# 8.0) allow you to produce and consume sequences of data asynchronously using IAsyncEnumerable<T> and await foreach.
using System;using System.Collections.Generic;using System.Threading.Tasks;
public class DataProducer{ public async IAsyncEnumerable<int> GetDataAsync() { for (int i = 0; i < 10; i++) { await Task.Delay(100); yield return i; } }}
// Consumerpublic class Program{ public static async Task Main() { var producer = new DataProducer(); await foreach (var item in producer.GetDataAsync()) { Console.WriteLine(item); } }}Real-world usage example
Section titled “Real-world usage example”Reading large files line by line: Process each line asynchronously without loading the entire file.
Example: System.IO.Stream can be wrapped in an async stream.