0
0
C Sharp (C#)programming~30 mins

Async streams with IAsyncEnumerable in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Async streams with IAsyncEnumerable
📖 Scenario: You are building a simple program that simulates receiving messages one by one over time, like getting chat messages or sensor data.
🎯 Goal: Create an async stream using IAsyncEnumerable that yields messages with a delay, then consume and print each message asynchronously.
📋 What You'll Learn
Create an async method that returns IAsyncEnumerable<string> with 3 messages
Use await Task.Delay(1000) to simulate waiting between messages
Consume the async stream with await foreach to print each message
💡 Why This Matters
🌍 Real World
Async streams are useful when you receive data over time, like chat messages, sensor readings, or live logs.
💼 Career
Understanding async streams helps you write efficient, responsive applications that handle data without freezing the user interface.
Progress0 / 4 steps
1
Create async stream method
Create an async method called GetMessagesAsync that returns IAsyncEnumerable<string>. Inside it, use yield return to return these exact messages one by one: "Hello", "from", "async stream".
C Sharp (C#)
Need a hint?

Remember to mark the method as async and use IAsyncEnumerable<string> as the return type.

2
Add delay between messages
Inside the GetMessagesAsync method, add await Task.Delay(1000); before each yield return to wait 1 second between messages.
C Sharp (C#)
Need a hint?

Use await Task.Delay(1000); before each yield return to pause 1 second.

3
Consume async stream with await foreach
Create an async Main method. Inside it, use await foreach with variables message to iterate over GetMessagesAsync(). Inside the loop, print each message using Console.WriteLine(message);.
C Sharp (C#)
Need a hint?

Use await foreach inside an async Main method to read messages.

4
Print all messages from async stream
Run the program to print all messages from GetMessagesAsync(). The output should show each message on its own line with a 1 second pause between them.
C Sharp (C#)
Need a hint?

Run the program and watch the messages print one by one with delay.