Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#

What are asynchronus streams in C#?

Hammad Nasir

Overview

In versions of C# prior to 8.0, streams could not be consumed asynchronously. This can now be done, but the following restrictions apply on functions that return asynchronous streams:

  • The method is to be declared using the async modifier.
  • The method must be of the IAsyncEnumerable<T> return type, where T can be any data type.
  • The method returns successive elements by using the yield return statement.

The sequence that is returned by such a function is consumed via the await foreach statement.

Example

class Program {
  public static async System.Collections.Generic.IAsyncEnumerable<int> GenSeq(int start, int end) {
    for (int i = start; i <= end; i++) {
      await Task.Delay(1000);
      yield return i + 1;
    }
  }
  
  public static async Task Main() {
    await foreach (var num in GenSeq(1, 5)) {
      System.Console.WriteLine(num);
    }
  }
}

Output

1
2
3
4
5

In the example above, the GenSeq method generates a sequence of numbers specified by the start and end arguments. These numbers are produced after a delay of 1000 milliseconds or 1 second. The stream produced by the GenSeq function in line 10 is consumed via the await foreach statement, asynchronously.

RELATED TAGS

c#

CONTRIBUTOR

Hammad Nasir
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring