Async streams

If you have worked with async methods in C#, you might have noticed that returning streams is not possible, or is hard to achieve with existing features. This would, however, be a helpful feature, which would make development tasks much simpler. This is why C# 8 has introduced a new interface called IAsyncEnumerable. With this new interface, asynchronous streams of data can be returned. Let me explain a little bit more about this.

Before async streams, in the C# programming language an async method was not able to return a stream of data—it could could only return a single value.

Let's take a look at an example of code that doesn't use an async stream:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExploreVS
{
class Program
{
public static void Main(string[] args)
{
var numbers = GetNumbersAsync();
foreach(var n in GetSumOfNums(numbers))
{
Console.WriteLine(n);
}
Console.ReadKey();
}
public static IEnumerable<int> GetNumbersAsync()
{
List<int> a = new List<int>();
a.Add(1);
a.Add(2);
a.Add(3);
a.Add(4);
return a;
}
public static IEnumerable<int> GetSumOfNums(IEnumerable<int> nums)
{
var sum = 0;
foreach(var num in nums)
{
sum += num;
yield return sum;
}
}

}
}

With async streams, a stream of data can now be returned using IAsyncEnumerable. Let's take a look at the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExploreVS
{
class Program
{
public static async void Main(string[] args)
{
var numbers = GetNumbersAsync();
await foreach(var n in GetSumOfNums(numbers))
{
Console.WriteLine(n);
}
Console.ReadKey();
}
public static IEnumerable<int> GetNumbersAsync()
{
List<int> a = new List<int>();
a.Add(1);
a.Add(2);
a.Add(3);
a.Add(4);
return a;
}
public static async IAsyncEnumerable<int> GetSumOfNums(IAsyncEnumerable<int> nums)
{
var sum = 0;
await foreach(var num in nums)
{
sum += num;
yield return sum;
}
}

}
}

From the preceding example, we can see how we can use this new feature of C# to return asynchronous streams.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.141.212