Async Loop in C# | await foreach Example and Explanation

Async Loop in C# | await foreach Example and Explanation

⚙️ Understanding Async Loop in C#

Asynchronous programming in C# allows tasks to run in the background without blocking the main thread. This is particularly useful for I/O operations, API calls, and UI responsiveness. With C# 8.0 and later, you can use await foreach to loop over asynchronous data streams. This type of loop is often called an async loop.

📘 What is an Async Loop?

An async loop in C# uses await foreach to asynchronously iterate over an IAsyncEnumerable<T>. This means the loop can await asynchronous results between iterations. It’s ideal when fetching data from a remote service, streaming files, or handling large datasets piece by piece.

🔍 Why Use Async Loops?

  • Does not block the main thread
  • Efficient for handling data streams
  • Ideal for UI and API-heavy applications
  • Cleaner, more readable code using await foreach

📄 C# Example: Async Loop with Delay


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

class Program
{
    static async IAsyncEnumerable GetNumbersAsync()
    {
        for (int i = 1; i <= 5; i++)
        {
            await Task.Delay(500); // Simulate async work
            yield return i;
        }
    }

    static async Task Main(string[] args)
    {
        await foreach (var number in GetNumbersAsync())
        {
            Console.WriteLine($"Received: {number}");
        }
    }
}
    

📝 Sample Output

Received: 1
Received: 2
Received: 3
Received: 4
Received: 5

🧠 How It Works

  • GetNumbersAsync returns an IAsyncEnumerable<int> that yields values one by one.
  • await Task.Delay(500) simulates a delay or async operation for each item.
  • await foreach iterates the results as they become available without blocking.

Async loops in C# give you full control over data as it's being fetched or processed, making them perfect for APIs, cloud services, and streaming data. This approach improves responsiveness and allows better scalability for applications.

Post a Comment

Post a Comment (0)

Previous Post Next Post

ads

ads

Update cookies preferences