Bird
Raised Fist0
C Sharp (C#)programming~20 mins

Async streams with IAsyncEnumerable in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Async Stream Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of async stream enumeration
What is the output of this C# code that uses an async stream?
C Sharp (C#)
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

class Program
{
    static async IAsyncEnumerable<int> GetNumbersAsync()
    {
        for (int i = 1; i <= 3; i++)
        {
            await Task.Delay(10);
            yield return i;
        }
    }

    static async Task Main()
    {
        await foreach (var num in GetNumbersAsync())
        {
            Console.Write(num);
        }
    }
}
A123
BCompilation error
C3 2 1
D1 2 3
Attempts:
2 left
💡 Hint
Remember that await foreach prints each number as it is yielded without spaces.
🧠 Conceptual
intermediate
1:30remaining
Understanding IAsyncEnumerable behavior
Which statement about IAsyncEnumerable in C# is true?
AIAsyncEnumerable is a synchronous interface for streaming data.
BIAsyncEnumerable can only be used with synchronous foreach loops.
CIAsyncEnumerable requires all elements to be available before iteration starts.
DIAsyncEnumerable allows asynchronous iteration over a collection with await foreach.
Attempts:
2 left
💡 Hint
Think about how async streams help with data that arrives over time.
🔧 Debug
advanced
2:30remaining
Identify the runtime error in async stream code
What runtime error will this code produce when executed?
C Sharp (C#)
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

class Program
{
    static async IAsyncEnumerable<int> GenerateAsync()
    {
        for (int i = 0; i < 3; i++)
        {
            if (i == 1) throw new InvalidOperationException("Error at 1");
            yield return i;
        }
    }

    static async Task Main()
    {
        try
        {
            await foreach (var n in GenerateAsync())
            {
                Console.Write(n);
            }
        }
        catch (Exception ex)
        {
            Console.Write(ex.GetType().Name);
        }
    }
}
ANo output, program hangs
BNullReferenceException
CInvalidOperationException
DCompilation error
Attempts:
2 left
💡 Hint
Look at where the exception is thrown inside the async stream.
📝 Syntax
advanced
2:00remaining
Which code snippet correctly defines an async stream?
Select the code snippet that correctly defines an async stream method returning IAsyncEnumerable.
Aasync IAsyncEnumerable<int> StreamNumbers() { await Task.Delay(10); yield return 1; }
Basync Task<IAsyncEnumerable<int>> StreamNumbers() { yield return 1; }
CIAsyncEnumerable<int> StreamNumbers() { yield return 1; }
Dasync IAsyncEnumerable<int> StreamNumbers() { yield return 1; }
Attempts:
2 left
💡 Hint
An async stream method must be async and use yield return with await inside.
🚀 Application
expert
2:30remaining
How many items are produced by this async stream?
Given this async stream method, how many items will be produced when enumerated?
C Sharp (C#)
using System.Collections.Generic;
using System.Threading.Tasks;

async IAsyncEnumerable<int> ProduceItems()
{
    int count = 0;
    while (count < 5)
    {
        await Task.Delay(5);
        if (count % 2 == 0)
            yield return count;
        count++;
    }
}
A5
B3
C2
D4
Attempts:
2 left
💡 Hint
Count how many numbers from 0 to 4 are even.

Practice

(1/5)
1. What is the main purpose of using IAsyncEnumerable<T> in C#?
easy
A. To improve performance by using multiple threads automatically.
B. To create synchronous collections that support LINQ queries.
C. To handle exceptions in synchronous methods.
D. To asynchronously stream data one item at a time without blocking.

Solution

  1. Step 1: Understand async streams concept

    IAsyncEnumerable<T> allows data to be produced and consumed asynchronously, item by item.
  2. Step 2: Compare with other options

    Options B, C, and D describe synchronous collections, exception handling, or threading, which are not the main purpose of IAsyncEnumerable<T>.
  3. Final Answer:

    To asynchronously stream data one item at a time without blocking. -> Option D
  4. Quick Check:

    Async streams = async item-by-item data [OK]
Hint: Async streams deliver data piecewise without blocking [OK]
Common Mistakes:
  • Confusing async streams with synchronous collections
  • Thinking it automatically uses multiple threads
  • Believing it handles exceptions directly
2. Which of the following is the correct syntax to consume an async stream named GetNumbersAsync()?
easy
A. foreach (var num in GetNumbersAsync()) { Console.WriteLine(num); }
B. await foreach (var num in GetNumbersAsync()) { Console.WriteLine(num); }
C. for await (var num in GetNumbersAsync()) { Console.WriteLine(num); }
D. async foreach (var num in GetNumbersAsync()) { Console.WriteLine(num); }

Solution

  1. Step 1: Recall async stream consumption syntax

    To consume IAsyncEnumerable<T>, use await foreach to await each item asynchronously.
  2. Step 2: Check each option

    foreach (var num in GetNumbersAsync()) { Console.WriteLine(num); } misses await, so it won't compile. for await (var num in GetNumbersAsync()) { Console.WriteLine(num); } uses invalid syntax for await. async foreach (var num in GetNumbersAsync()) { Console.WriteLine(num); } uses invalid keyword async foreach.
  3. Final Answer:

    await foreach (var num in GetNumbersAsync()) { Console.WriteLine(num); } -> Option B
  4. Quick Check:

    Use await foreach to read async streams [OK]
Hint: Always use 'await foreach' to read IAsyncEnumerable streams [OK]
Common Mistakes:
  • Omitting 'await' before foreach
  • Using 'for await' instead of 'await foreach'
  • Writing 'async foreach' which is invalid
3. What will be the output of the following code?
async IAsyncEnumerable<int> GetNumbers()
{
    for (int i = 1; i <= 3; i++)
    {
        await Task.Delay(10);
        yield return i;
    }
}

async Task Run()
{
    await foreach (var n in GetNumbers())
    {
        Console.Write(n);
    }
}

Run().GetAwaiter().GetResult();
medium
A. No output
B. 1 2 3
C. 123
D. Task not awaited error

Solution

  1. Step 1: Understand the async stream generation

    The method yields numbers 1, 2, 3 with a small delay between each.
  2. Step 2: Analyze the output in Run()

    The await foreach prints each number without spaces or newlines, so output is "123".
  3. Final Answer:

    123 -> Option C
  4. Quick Check:

    Yielded numbers print consecutively as '123' [OK]
Hint: Yielded async items print in order without spaces by default [OK]
Common Mistakes:
  • Expecting spaces between numbers
  • Thinking the delay prevents output
  • Assuming an error due to async usage
4. Identify the error in this async stream method:
async IAsyncEnumerable<int> CountToThree()
{
    for (int i = 1; i <= 3; i++)
    {
        Task.Delay(10);
        yield return i;
    }
}
medium
A. Missing await before Task.Delay(10);
B. Cannot use yield return in async methods
C. Return type should be Task<IAsyncEnumerable<int>>
D. for loop syntax is incorrect

Solution

  1. Step 1: Check async delay usage

    Task.Delay(10) returns a task but is not awaited, so delay does not pause execution.
  2. Step 2: Validate yield return in async streams

    Using yield return in async IAsyncEnumerable<T> is valid, so Cannot use yield return in async methods is wrong.
  3. Final Answer:

    Missing await before Task.Delay(10); -> Option A
  4. Quick Check:

    Await async calls inside async streams [OK]
Hint: Always await async calls like Task.Delay inside async streams [OK]
Common Mistakes:
  • Forgetting to await Task.Delay
  • Thinking yield return is invalid in async streams
  • Confusing return type with Task<IAsyncEnumerable>
5. You want to create an async stream that yields only even numbers from 1 to 10 with a small delay between each yield. Which implementation correctly does this?
hard
A. async IAsyncEnumerable<int> EvenNumbers() { for (int i = 2; i <= 10; i += 2) { await Task.Delay(10); yield return i; } }
B. async IAsyncEnumerable<int> EvenNumbers() { for (int i = 1; i <= 10; i++) { if (i % 2 == 0) yield return i; } }
C. IAsyncEnumerable<int> EvenNumbers() { for (int i = 2; i <= 10; i += 2) yield return i; }
D. async Task<IAsyncEnumerable<int>> EvenNumbers() { for (int i = 2; i <= 10; i += 2) yield return i; }

Solution

  1. Step 1: Check async stream signature and yield

    Async streams must be declared as async IAsyncEnumerable<T> and use yield return inside.
  2. Step 2: Validate each option

    async IAsyncEnumerable<int> EvenNumbers() { for (int i = 1; i <= 10; i++) { if (i % 2 == 0) yield return i; } } lacks an async delay, so it is incomplete. async IAsyncEnumerable<int> EvenNumbers() { for (int i = 2; i <= 10; i += 2) { await Task.Delay(10); yield return i; } } correctly uses async IAsyncEnumerable<int>, awaits delay, and yields even numbers. IAsyncEnumerable<int> EvenNumbers() { for (int i = 2; i <= 10; i += 2) yield return i; } is missing async and await, so not an async stream. async Task<IAsyncEnumerable<int>> EvenNumbers() { for (int i = 2; i <= 10; i += 2) yield return i; } returns Task<IAsyncEnumerable> which is incorrect for async streams.
  3. Final Answer:

    async IAsyncEnumerable<int> EvenNumbers() { for (int i = 2; i <= 10; i += 2) { await Task.Delay(10); yield return i; } } -> Option A
  4. Quick Check:

    Async streams need async keyword and await inside [OK]
Hint: Async streams require async keyword and await inside loops [OK]
Common Mistakes:
  • Omitting await inside async streams
  • Returning Task<IAsyncEnumerable> instead of IAsyncEnumerable
  • Not marking method async when using yield return asynchronously
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard