Asynchronous Programming in C#: Mastering `async`/`await` and `yield return`

Discover the power of asynchronous programming in C# with this in-depth guide. Learn how to use async/await to write responsive, non-blocking code, and explore custom async methods for advanced scenarios. The article also introduces `yield return` for lazy evaluation, helping you optimize performance when working with large data sets or complex processes. By the end, you'll have a solid understanding of how to write efficient, scalable asynchronous programs in C#.

by Gautham Pai · · 1 min read

← Back to Articles

Using async/await

C# provides the async and await keywords to simplify asynchronous programming:

public class Program
{
    public static async Task Main()
    {
        StreamReader reader = new StreamReader("people");
        string fileContents = await reader.ReadToEndAsync();
        Console.WriteLine(fileContents);
        Console.WriteLine("This line is after ReadToEndAsync");
    }
}

Writing Custom Async Methods

You can wrap existing asynchronous methods in custom methods:

public static async Task<string> ReadFileAsync(string filename)
{
    StreamReader reader = new StreamReader(filename);
    Task<string> result = reader.ReadToEndAsync();
    Console.WriteLine("This runs before the read is complete");
    return await result;
}

yield return

Introduction to yield return

The yield return statement allows you to return one element at a time in an iterator:

public static IEnumerable<int> GetNextValue()
{
    int i = 1;
    yield return i;
    i += 1;
    yield return i;
    i += 1;
    yield return i;
}

Lazy Evaluation with Yield Return

You can implement lazy evaluation using yield return, which defers execution until the value is needed:

public static IEnumerable<int> LazyMap(IEnumerable<int> inputList, Func<int, int> operation)
{
    foreach (var item in inputList)
    {
        yield return operation(item);
    }
}

Test Your Knowledge

No quiz available

Topics