Microsoft promised us another great feature in C# 8 – async streams. And believe me or not, it was first discussed in… 2015! In this short post I will try to explain the idea and purpose of this new C# 8 planned feature.
Sis, you think I will use it?
Yes, if you are about to:
- write a code for IoT devices that streams data.
- in any other scenario, when you want to get data in packages and without blocking the main thread
- consume the data from a source that works in slower manner than you can consume it.
Just a few examples ?.
How will it work?
Well, imagine you are the source of data. You write an async method and because you want the lazy approach (because when you are lazy, your code should be lazy too, right? Hahaha, OMG! Haha, yeah, weak jokes are my speciallity). So, because you planned a lazy approach, you return data with ‘yield return’. Something like this:
async Task<IEnumerable<int>> GetNumbersDividedByAsyncEnumerable(int divider, int maxNumber) { for (int i = 0; i < maxNumber; i++) { if (i % divider == 0) { yield return i; } } }
At this moment, Visual Studio will shout at you, telling that “The body of ‘Program.GetNumbersDividedByAsyncEnumerable(int, int)’ cannot be an iterator block because ‘Task>’ is not an iterator interface type”. What a mean asshole! 😉
Because of this inconvenience, soon we will be able to change IEnumerable to IAsyncEnumerable and that way return enumerable package in async method. Sounds good, isn’t it? So our data source will look like this:
async IAsyncEnumerable<int> GetNumbersDividedByAsyncEnumerable_CS8(int divider, int maxNumber) { for (int i = 0; i < maxNumber; i++) { if (i % divider == 0) { yield return i; } } }
And consuming the data will look like this:
await foreach (var result in GetNumbersDividedByAsyncEnumerable_CS8(3, 100)) { Console.WriteLine(x); }
The dark side of C# 8 😉
If you find this feature interesting and usefull don’t be too happy ;). Asynchronous streams will be part of .Net Standard 2.1 so… Will be unavailable in .Net Framework 4.8 (or older, of course). Due to the pressure put on the .Net Framework stability, Microsoft decided to make us using .Net Standard 2.1 (so choosing .Net Core 3.0, Xamarin, Mono etc. over ‘old school’ .Net) to be able to use async streams. Yeah, that’s sad but understandable.
If you find this C# 8 feature interesting, take a look at the following blogs, that describes the topic deeper:
https://www.infoq.com/articles/Async-Streams
https://www.infoq.com/news/2017/05/async-streams