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:
async
modifier.IAsyncEnumerable<T>
return type, where T
can be any data type.yield return
statement.The sequence that is returned by such a function is consumed via the await foreach
statement.
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); } } }
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
CONTRIBUTOR
View all Courses