0
0
C Sharp (C#)programming~7 mins

Async streams with IAsyncEnumerable in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Async streams let you get data one piece at a time without waiting for everything. This helps when working with data that comes slowly or in parts.

When reading large files or data from the internet without blocking your program.
When you want to process data as it arrives, like messages or sensor readings.
When you want to save memory by not loading all data at once.
When working with databases or APIs that return data in chunks.
When you want to improve app responsiveness by handling data asynchronously.
Syntax
C Sharp (C#)
async IAsyncEnumerable<T> MethodName()
{
    yield return value1;
    await Task.Delay(1000); // simulate async work
    yield return value2;
}

IAsyncEnumerable<T> is like a list you can get items from one by one asynchronously.

Use await foreach to read from an async stream.

Examples
This method counts from 1 to 3, waiting a bit before giving each number.
C Sharp (C#)
async IAsyncEnumerable<int> CountToThreeAsync()
{
    for (int i = 1; i <= 3; i++)
    {
        await Task.Delay(500); // wait half a second
        yield return i;
    }
}
This code reads numbers from the async stream and prints them as they arrive.
C Sharp (C#)
await foreach (var number in CountToThreeAsync())
{
    Console.WriteLine(number);
}
Sample Program

This program creates an async stream that produces numbers 1 to 5 with a short delay. The main method reads and prints each number as it arrives.

C Sharp (C#)
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

class Program
{
    static async IAsyncEnumerable<int> GenerateNumbersAsync()
    {
        for (int i = 1; i <= 5; i++)
        {
            await Task.Delay(300); // simulate delay
            yield return i;
        }
    }

    static async Task Main()
    {
        await foreach (var number in GenerateNumbersAsync())
        {
            Console.WriteLine($"Number: {number}");
        }
    }
}
OutputSuccess
Important Notes

Async streams help keep your app responsive by not blocking while waiting for data.

Remember to use await foreach to consume IAsyncEnumerable<T>.

You can combine async streams with cancellation tokens to stop reading early.

Summary

Async streams let you get data piece by piece asynchronously.

Use IAsyncEnumerable<T> to create async streams and await foreach to read them.

This helps with large or slow data sources without freezing your app.