C# async streams : When to use await before foreach ?

T.Zacks 3,986 Reputation points
2022-10-13T12:57:14.577+00:00

see the code

C# 8.0 introduces async streams, which model a streaming source of data. Data streams often retrieve or generate elements asynchronously. Async streams rely on new interfaces introduced in .NET Standard 2.1. These interfaces are supported in .NET Core 3.0 and later. They provide a natural programming model for asynchronous streaming data sources.

public class Program  
{  
    public static async Task Main()  
    {  
        List<int> numbers = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };  

        await foreach(int number in YieldReturnNumbers(numbers))  
        {  
            Console.WriteLine(number);  
        }  
    }  

    public static async IAsyncEnumerable<int> YieldReturnNumbers(List<int> numbers)   
    {  
        foreach (int number in numbers)  
        {  
            await Task.Delay(1000);  
            yield return number;  
        }  
    }  
}  

1) why await used before foreach keyword ?
2) without delay can't we use yield return number; ?

code taken from https://stackoverflow.com/a/69866729

thanks

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,386 Reputation points
    2022-10-13T21:43:58.22+00:00
    1. For demoing
    2. Yes without await as there is nothing to await
    0 comments No comments

  2. Hanim Ali V Hyder Ali 1 Reputation point
    2022-12-01T09:20:02.017+00:00

    To better understand I used a random number in Task.Delay like below.

    var random = new Random();
    var rNum = random.Next(1, 5);
    await Task.Delay(TimeSpan.FromSeconds(rNum));

    I was expecting the numbers would be printed in order of short wait. Or in other words, while we await for Task.Delay, it would proceed to next loop (movenext()). So if in first iteration the rNum was 4, and in second rNum was 2, then second iteration console.writeline would happen first

    But, it looks like the iteration (movenext()) is blocked. How to achive iteration without blocking

    0 comments No comments