in Dot Net by
Q:
Asynchronous streams in C#

▼ Show 1 Answer

0 votes
by

Starting with C# 8.0, you can create and consume streams asynchronously. A method that returns an asynchronous stream has three properties:

  1. It's declared with the async modifier.
  2. It returns an IAsyncEnumerable<T>.
  3. The method contains yield return statements to return successive elements in the asynchronous stream.

Consuming an asynchronous stream requires you to add the await keyword before the foreach keyword when you enumerate the elements of the stream. Adding the await keyword requires the method that enumerates the asynchronous stream to be declared with the async modifier and to return a type allowed for an async method. Typically that means returning a Task or Task<TResult>. It can also be a ValueTask or ValueTask<TResult>. A method can both consume and produce an asynchronous stream, which means it would return an IAsyncEnumerable<T>. The following code generates a sequence from 0 to 19, waiting 100 ms between generating each number:

public static async System.Collections.Generic.IAsyncEnumerable<int> GenerateSequence()

{

    for (int i = 0; i < 20; i++)

    {

        await Task.Delay(100);

        yield return i;

    }

}

Learn More with Madanswer

Related questions

+1 vote
asked Feb 15, 2020 in JAVA by rahuljain1
  • #asynchronous-streams
0 votes
asked Dec 8, 2019 in Dot Net by Sinaya
0 votes
...