C# 8 officially got released on 23rd Sep 2019 along with .NET Core 3.0 and Visual Studio 2019 v16.3. It has several new features and enhancements to give more power to developers and make their day to day coding even easier.
I have started writing a series of articles to go through the new C# 8 features one by one to cover all the new features and enhancements. In case you have not gone through my previous articles on C# 8, you may go through as follows.
- Working With Default Interface Implementation In C# 8.0
- Working With Ranges And Indices In C# 8.0
- Working With Switch Expressions And Pattern Matching In C# 8.0
- Working With Nullable Reference Types In C# 8.0
In this article, we will go through the Async Stream and Static local functions.
Async streams
Among other features, Async streams are also one of the important features introduced in C# 8. It provides the ability to asynchronously access the stream of data that was not available earlier. Now you can create and use the streams asynchronously.
Async streams have a couple of characteristics as follows.
- It's declared with the async modifier and returns an IAsyncEnumerable<T>.
- The method contains yield return statements to return successive elements in the asynchronous stream of data.
The async and await based programming model was one of the major innovations of C# 5 and async streams is yet another enhancement on top of async and await pattern to write asynchronous code in a more intuitive way. With async streams developer now can easily implement asynchronous streams of data and also iterate asynchronously using a foreach loop. This is possible by the introduction of the new interfaces IAsyncEnumerable<T> and IAsyncDisposable<T>.
Let's have a look at the code below to understand how to work with async streams.
- public static async Task ExecuteAsyncStream() {
- await foreach(var number in GenerateSequence()) {
- Console.WriteLine($ "The square of number {number.Number} is: {
- number.Square
- }
- ");
- }
- }
- public static async IAsyncEnumerable < SquareNumber > GenerateSequence() {
- for (int i = 1; i <= 10; i++) {
- await Task.Delay(200);
- yield
- return new SquareNumber {
- Number = i, Square = i * i
- };
- }
- }
- public class SquareNumber {
- public int Number {
- get;
- set;
- }
- public int Square {
- get;
- set;
- }
- }


Sourav Kumar DasPosted Oct 29, 2019, 11:49 PM
Nice Article Sir.