c# IAsyncEnumerable
In newer C# versions, you can use `await foreach` with `IAsyncEnumerable<T>` to yield results asynchronously instead of using `IEnumerable<T>`. This is particularly useful when dealing with large data sets, streaming data, or async operations like database queries or API calls.
Sample code :-
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
await foreach (var item in GetNumbersAsync())
{
Console.WriteLine(item);
}
}
static async IAsyncEnumerable<int> GetNumbersAsync()
{
for (int i = 1; i <= 5; i++)
{
await Task.Delay(1000); // Simulating an async operation
yield return i;
}
}
}
Comments