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

Stream vs async stream behavior in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Streams let you handle data one piece at a time. Async streams do this too, but they work well when data comes slowly or from a remote place.

Reading a large file piece by piece without loading it all at once.
Processing data from a network where data arrives over time.
Handling user input events that come one after another.
Working with data from a database query that returns results gradually.
Syntax
C Sharp (C#)
IEnumerable<T> GetStream() { ... }  // for normal stream
IAsyncEnumerable<T> GetAsyncStream() { ... }  // for async stream

IEnumerable<T> is for synchronous streams.

IAsyncEnumerable<T> is for asynchronous streams and requires await foreach to read.

Examples
This is a normal stream that returns numbers one by one.
C Sharp (C#)
IEnumerable<int> GetNumbers()
{
    yield return 1;
    yield return 2;
    yield return 3;
}
This async stream returns numbers with a delay, simulating slow data arrival.
C Sharp (C#)
async IAsyncEnumerable<int> GetNumbersAsync()
{
    yield return 1;
    await Task.Delay(1000);
    yield return 2;
    await Task.Delay(1000);
    yield return 3;
}
Sample Program

This program shows how to read from a normal stream and an async stream. The async stream waits a bit before giving each number.

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

class Program
{
    static IEnumerable<int> GetNumbers()
    {
        yield return 1;
        yield return 2;
        yield return 3;
    }

    static async IAsyncEnumerable<int> GetNumbersAsync()
    {
        yield return 1;
        await Task.Delay(500);
        yield return 2;
        await Task.Delay(500);
        yield return 3;
    }

    static async Task Main()
    {
        Console.WriteLine("Synchronous stream output:");
        foreach (var num in GetNumbers())
        {
            Console.WriteLine(num);
        }

        Console.WriteLine("\nAsynchronous stream output:");
        await foreach (var num in GetNumbersAsync())
        {
            Console.WriteLine(num);
        }
    }
}
OutputSuccess
Important Notes

Use foreach for normal streams and await foreach for async streams.

Async streams help keep your app responsive when waiting for data.

Summary

Streams let you process data step-by-step.

Async streams work well when data comes slowly or from outside your program.

Use IEnumerable<T> with foreach and IAsyncEnumerable<T> with await foreach.