What is Async Stream in C#: Explanation and Example
async stream in C# is a way to produce and consume data asynchronously over time using IAsyncEnumerable<T>. It allows you to await each item as it arrives, making it ideal for handling sequences of data that come in slowly or from asynchronous sources.How It Works
Imagine you are waiting for a series of letters to arrive in the mail, but you don't know exactly when each one will come. Instead of waiting for all letters to arrive before reading them, you open and read each letter as soon as it arrives. This is similar to how async streams work in C#.
An async stream lets you receive data items one by one asynchronously. Instead of blocking your program while waiting for all data, you can process each item as it becomes available. This is done using the IAsyncEnumerable<T> interface and the await foreach loop.
Under the hood, the async stream uses asynchronous iteration, which means it can pause and resume while waiting for the next item, making your program more responsive and efficient when dealing with slow or large data sources.
Example
This example shows how to create an async stream that produces numbers with a delay, and how to consume it using await foreach.
using System; using System.Collections.Generic; using System.Threading.Tasks; class Program { static async IAsyncEnumerable<int> GetNumbersAsync() { for (int i = 1; i <= 5; i++) { await Task.Delay(500); // Simulate asynchronous work yield return i; } } static async Task Main(string[] args) { await foreach (var number in GetNumbersAsync()) { Console.WriteLine($"Received number: {number}"); } } }
When to Use
Use async streams when you need to handle data that arrives over time and you want to process each piece as soon as it is ready without blocking your program. This is common in scenarios like reading data from a network, processing user input events, or working with large data sets that are loaded in chunks.
For example, if you are downloading parts of a file from the internet or reading lines from a log file as they are written, async streams let you start working with the data immediately instead of waiting for everything to finish.
Key Points
- Async streams use
IAsyncEnumerable<T>to produce data asynchronously. - You consume async streams with
await foreach, which waits for each item. - They improve responsiveness by processing data as it arrives instead of waiting for all data.
- Ideal for slow or large data sources like network streams or user events.