Monday, March 4, 2019

IAsyncEnumerable<T> in C# 8

Before C# 8, if you want to iterate over a collection, the data for that collection needs to be ready before iteration.

Basically, something like this was not possible prior to C# 8.
private static async IEnumerable<string> GetDataAsync()
{
    for (var i = 0; i < 10; i++)
    {
        yield return await GetDataAsync(i);
    }
}
What you can do is something like below.
private static IEnumerable<string> GetDataAsync()
{
    for (var i = 0; i < 10; i++)
    {
        yield return GetDataAsync(i).Result;
    }
}
But this will cause a thread block. With C# 8 comes the IAsyncEnumerable<T> which makes the yield return asynchronous.
private static async IAsyncEnumerable<string> GetDataAsync()
{
    for (var i = 0; i < 10; i++)
    {
        yield return await GetDataAsync(i);
    }
}
You can see that even though it’s an async method, it’s not returning a Task anymore. You can iterate over an IAsyncEnumerable<T> using await foreach making it an async stream.
await foreach (var item in GetDataAsync())
{     
     Console.WriteLine(item);
}
Isn’t it nice.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment