CodeBlanks Logo Icon CodeBlanks

Summary - Async basics

C# course · Advanced · Lesson 6/83

Combine async/await and Task.Run to write a parallel file reader.

Summary - Async basics

In this group you learned the basics of async/await: async marks a method, await waits for a Task, Task and Task<T> represent background work. With Task.Run you offload CPU work to the pool; Task.CompletedTask and Task.FromResult build deterministic Tasks.

The key lesson: use await instead of .Result in synchronous code to avoid deadlock. Now we will combine all of this in a small app.

Exercise Async greeting app

Define a static async Task<string> Greet(string name) method. In its body write await Task.CompletedTask and return "Hello, " + name;. Make Main a static async Task Main. Call it with string msg = await Greet("Alex"); and print with Console.WriteLine(msg);.

Show example solution
In Greet body write await Task.CompletedTask and return "Hello, " + name. Make Main static async Task Main() and write string msg = await Greet("Alex"); Console.WriteLine(msg);
Example solution:
using System;
using System.Threading.Tasks;

class Program
{
    static async Task<string> Greet(string name)
    {
        await Task.CompletedTask;
        return "Hello, " + name;
    }

    static async Task Main()
    {
        string msg = await Greet("Alex");
        Console.WriteLine(msg);
    }
}

Tips

A few tips: always return Task or Task<T> from async methods; avoid void. Make Main an async Task and use await directly. Do not use .Result or .Wait() in synchronous code.

For CPU work use Task.Run; for I/O call an async method directly. In tests use Task.FromResult and Task.CompletedTask for deterministic results.

Exercise Mini app: Async counter

Define static async Task<int> Compute(). In its body write await Task.CompletedTask and return 6 * 7;. Make Main a static async Task Main. Call it with int answer = await Compute(); and print with Console.WriteLine("Answer: " + answer);.

Show example solution
" + answer);
Example solution:
using System;
using System.Threading.Tasks;

class Program
{
    static async Task<int> Compute()
    {
        await Task.CompletedTask;
        return 6 * 7;
    }

    static async Task Main()
    {
        int answer = await Compute();
        Console.WriteLine("Answer: " + answer);
    }
}

Test yourself

  1. Which keyword marks an async method?

    • async
    • await
    • Task
    • Run
    Show answer

    async — Correct. The async keyword marks the method.

All lessons in Advanced