IAsyncEnumerable<T>

Ercan Erdoğan
2 min readFeb 12, 2024

--

IAsyncEnumerable is a new interface introduced in C# 8.0 that allows you to work with asynchronous streams of data. It is similar to IEnumerable, but it has some advantages, such as:

  • It supports asynchronous streaming, which means that you can start processing the data as soon as it is available, without waiting for the entire collection to be loaded in memory.
  • It uses a pull-based approach, which means that the next item is fetched or created only when requested by the consumer, which reduces the memory usage and improves the performance.
  • It can work with out-of-memory collections, such as databases or web services, and translate the query expression into the native language of the data source, such as SQL.

We can use IAsyncEnumerable when we need to process large or infinite sequences of data in an asynchronous manner, such as real-time data feeds, web requests, or file streams. We can also use the async and await keywords to write asynchronous code that is easy to read and maintain.

Here is an example of how we can use IAsyncEnumerable to generate a sequence of random numbers asynchronously:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace AsyncDemo
{
class Program
{
static async Task Main(string[] args)
{
// Create an instance of the RandomNumberGenerator class
var rng = new RandomNumberGenerator();

// Use a foreach loop to iterate over the IAsyncEnumerable<int> returned by the GetNumbers method
await foreach (var number in rng.GetNumbers(10))
{
// Print the number to the console
Console.WriteLine(number);
}
}
}

// Define a class that implements the IAsyncEnumerable<int> interface
class RandomNumberGenerator : IAsyncEnumerable<int>
{
// Define a private field to store a Random object
private Random random;

// Define a constructor that initializes the random field
public RandomNumberGenerator()
{
random = new Random();
}

// Define a method that returns an IAsyncEnumerator<int> object
public async IAsyncEnumerator<int> GetAsyncEnumerator()
{
// Use a while loop to generate random numbers indefinitely
while (true)
{
// Generate a random number between 0 and 100
var number = random.Next(0, 101);

// Yield the number to the consumer
yield return number;

// Wait for one second before generating the next number
await Task.Delay(1000);
}
}
}
}

The output of the program is: The numbers below will be written in the console one by one without waiting to finish the loop.

42
76
13
98
54
67
23
89
12
45

Some use cases in which we can use IAsyncEnumerable

  • Real-time data feeds, such as stock prices, sensor readings, or social media updates. You can use IAsyncEnumerable to stream the data as it arrives, without blocking the UI thread or consuming too much memory.
  • Web requests, such as downloading files, fetching data from APIs, or scraping web pages. You can use IAsyncEnumerable to make concurrent requests and process the responses as they come, without waiting for all of them to finish.
  • File streams, such as reading or writing large files, parsing CSV or JSON files, or compressing or encrypting files. You can use IAsyncEnumerable to read or write the file chunks asynchronously, without loading the entire file into memory.

Resources:

--

--