JavaRush /Courses /C# SELF /Synchronous and asynchronous generators in C# ( yield)

Synchronous and asynchronous generators in C# ( yield)

C# SELF
Level 62, Lesson 1
Available

1. Introduction

Imagine you need to process a gigantic log file with millions of lines, or generate an incredibly long sequence of numbers. How would you do that without generators?

The traditional approach would look like this:


// Problem: generates the whole collection in memory at once
List<int> GenerateAllNumbersSync(int count)
{
    List<int> numbers = new List<int>();
    for (int i = 0; i < count; i++)
    {
        numbers.Add(i);
    }
    return numbers; // Return when everything is ready
}

// Usage:
var myNumbers = GenerateAllNumbersSync(1_000_000); // 1 million numbers in memory at once!
foreach (var num in myNumbers) { /* Processing */ }

What's wrong here?

  1. Memory consumption: If count is very large, the whole collection is created in memory, which can lead to OutOfMemoryException.
  2. Latency: The user or the next part of the program has to wait until all data is fully generated and loaded into memory.
  3. Infinite sequences: This approach simply doesn't work if the sequence can be potentially infinite.

Enter generators! They implement the concept of lazy evaluation and streaming. Instead of producing all data at once, a generator yields elements one by one, only when they are actually needed.

2. Generator basics

In C# generators are created using the special keyword yield.

What is a Generator?

It's a method, a property's get block or an operator that contains one or more yield return expressions.

yield return

This is the heart of generators. When the compiler encounters yield return:

  1. The element specified after yield return is handed to the caller.
  2. The generator method's execution is suspended, and its current state (where it is in the loop, values of local variables) is saved.
  3. On the next request for an element (for example, the next iteration of a foreach), the method resumes execution from where it was suspended.

Return type: A generator method must return IEnumerable<T> or IEnumerator<T>. The compiler generates all the required "magic" for you.


// Example 2.1: Simple number generator
IEnumerable<int> GenerateNumbers(int count)
{
    Console.WriteLine("Start generating...");
    for (int i = 0; i < count; i++)
    {
        Console.WriteLine($"Generating: {i}");
        yield return i; // Suspend and return element
    }
    Console.WriteLine("Generation finished.");
}

// Usage:
// Note that "Start generating..." will appear only on the first iteration!
// And "Generating: X" — on each new iteration.
foreach (var num in GenerateNumbers(3))
{
    Console.WriteLine($"Received in foreach: {num}");
}

yield break

Used to terminate iteration early. After yield break no more elements will be returned. If execution reaches the end of the method, an explicit yield break is not necessary.


// Example 2.2: Generator with an exit condition
IEnumerable<string> GetFirstNElements(List<string> source, int n)
{
    int count = 0;
    foreach (var item in source)
    {
        if (count >= n)
        {
            yield break; // Exit the generator
        }
        yield return item;
        count++;
    }
}

// Usage:
// var fruits = new List<string> { "Apple", "Banana", "Orange", "Grape" };
// foreach (var fruit in GetFirstNElements(fruits, 2))
// {
//     Console.WriteLine(fruit); // Will print "Apple", "Banana"
// }

3. State machine

How does this work "under the hood"? There's no magic — just smart compiler work.

When you write a method with yield, the C# compiler transforms it into a class that implements IEnumerator<T> and IEnumerable<T>. This generated class is the state machine.

  • State preservation: the machine stores a state number (where it stopped) and the values of all local variables at the suspension point.
  • Iteration: when iterating via foreach, MoveNext() is called and the Current property is read. MoveNext() resumes execution until the next yield return/yield break, and Current returns the current element.

Effectively the compiler implements the Iterator Pattern for you.

4. Using generators

Example: Processing large amounts of data

Reading a file line by line without loading the whole file into memory.


// Simulating reading a big file
IEnumerable<string> ReadBigFileLines(string filePath)
{
    Console.WriteLine($"Opening file: {filePath}");
    // In a real app this would be a StreamReader
    yield return "Data line 1";
    yield return "Data line 2";
    yield return "Data line 3";
    Console.WriteLine("Finished simulating file read.");
}

// Usage:
Console.WriteLine("Start processing.");
foreach (var line in ReadBigFileLines("my_huge_log.txt"))
{
    Console.WriteLine($"Processed line: {line}");
    if (line.Contains("2")) break; // We can stop whenever we want
}
Console.WriteLine("Processing finished.");

Note that the final message will appear only after the iteration completes.

Example: Infinite sequences


IEnumerable<long> FibonacciSequence()
{
    long a = 0;
    long b = 1;
    while (true) // Potentially infinite sequence
    {
        yield return a;
        long temp = a;
        a = b;
        b = temp + b;
    }
}

// Usage:
int count = 0;
foreach (var num in FibonacciSequence())
{
    Console.WriteLine(num);
    count++;
    if (count >= 10) break; // We must limit so we don't hang
}

Example: Data processing pipelines

Building chains of methods where each step processes data "on the fly".


IEnumerable<int> GetNumbers()
{
    yield return 1; yield return 2; yield return 3; yield return 4; yield return 5;
}

IEnumerable<int> FilterEven(IEnumerable<int> source)
{
    foreach (var num in source)
    {
        if (num % 2 == 0) yield return num;
    }
}

IEnumerable<int> Square(IEnumerable<int> source)
{
    foreach (var num in source)
    {
        yield return num * num;
    }
}

// Usage:
foreach (var result in Square(FilterEven(GetNumbers())))
{
    Console.WriteLine(result); // 4, 16
}

This is very similar to how many LINQ operators work (for example, Where, Select, Take, Skip).

5. Asynchronous generators

Synchronous generators are great, but what if each element requires an asynchronous operation (e.g., a network request)? Before C# 8.0 this was hard to do.

Problem: Asynchronous data streams

You can't use await inside a synchronous generator method.


// This WILL NOT COMPILE!
IEnumerable<string> GetStringsAsyncProblem()
{
    await Task.Delay(100); // Error: await can only be used in an async method
    yield return "Hello";
}

Solution: IAsyncEnumerable<T> and await foreach

  • IAsyncEnumerable<T> — the async counterpart to IEnumerable<T>.
  • await foreach — a convenient syntax to iterate an asynchronous sequence (internally calls MoveNextAsync() and handles async state).

async yield return

Now you can use yield return inside an async method that returns IAsyncEnumerable<T>. The compiler will build an asynchronous state machine.


// Example 5.1: Asynchronous number generator
async IAsyncEnumerable<int> GenerateNumbersAsync()
{
    Console.WriteLine("Start async generation...");
    for (int i = 0; i < 5; i++)
    {
        await Task.Delay(100); // Simulate async work (e.g., network call)
        Console.WriteLine($"Asynchronously generating: {i}");
        yield return i; // Return element
    }
    Console.WriteLine("Async generation finished.");
}

// Usage:
async Task ConsumeAsyncNumbers()
{
    Console.WriteLine("Start async processing...");
    await foreach (var number in GenerateNumbersAsync())
    {
        Console.WriteLine($"Asynchronously received: {number}");
    }
    Console.WriteLine("Async processing finished.");
}

// Run:
await ConsumeAsyncNumbers(); // Call this from async Main or a similar context

IAsyncDisposable and await using (in the context of generators)

If a generator opens a resource that is disposed asynchronously (DisposeAsync()), use await using. When await foreach completes it will automatically call DisposeAsync() on the inner iterator if it implements IAsyncDisposable.


// Example 5.2: Async file reading with await using
// Real StreamReader implements IAsyncDisposable
async IAsyncEnumerable<string> ReadFileLinesAsync(string filePath)
{
    Console.WriteLine($"[Generator] Opening file asynchronously: {filePath}");
    // await using ensures DisposeAsync() is called after the block exits
    await using var reader = new StreamReader(filePath); 
    
    string? line;
    while ((line = await reader.ReadLineAsync()) != null) // Async line read
    {
        yield return line;
    }
    Console.WriteLine($"[Generator] Finished reading file: {filePath}");
}

// Usage:
async Task ProcessFileAsync()
{
    Console.WriteLine("[Handler] Start processing file.");
    await foreach (var line in ReadFileLinesAsync("path_to_some_file.txt")) // replace with a real path
    {
        Console.WriteLine($"[Handler] Received line: {line}");
        // You can do async processing per line here
        await Task.Delay(50); 
    }
    Console.WriteLine("[Handler] File processing finished.");
}

// Run:
await ProcessFileAsync(); // Call this from async Main

Cancelling async generators: CancellationToken

Add a CancellationToken to async generators so the caller can cancel generation.


// Example 5.3: Async generator with cancellation
async IAsyncEnumerable<int> GenerateCancelableSequence(
    int start, int count, 
    [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken token = default)
{
    for (int i = 0; i < count; i++)
    {
        token.ThrowIfCancellationRequested(); // Check cancellation token
        await Task.Delay(100, token); // Task.Delay supports cancellation too
        yield return start + i;
    }
}

Usage


var cts = new CancellationTokenSource();
Task.Run(async () =>
{
    await Task.Delay(300); // Let the generator run a bit
    cts.Cancel(); // Cancel!
});

try
{
    await foreach (var num in GenerateCancelableSequence(0, 100, cts.Token))
    {
        Console.WriteLine($"Received: {num}");
    }
}
catch (OperationCanceledException)
{
    Console.WriteLine("Generation canceled.");
}

6. Limitations and when to be careful

Limitations of yield:

  • You can't use yield return in try blocks where catch or finally also contain yield.
  • Methods with yield cannot be unsafe.
  • You can't use yield in async void methods (use async Task or IAsyncEnumerable<T> instead).

Performance: For very small or fixed collections the overhead of the state machine might be slightly higher than returning a plain List<T>. But for large data sets the benefits of laziness and streaming are usually far more important.

Error handling: Exceptions thrown inside a generator will propagate to the caller and can be caught there just like in normal methods.

2
Task
C# SELF, level 62, lesson 1
Locked
Asynchronous Number Generator in a Range
Asynchronous Number Generator in a Range
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION