Codiqo

Learn C# · lesson 60 of 61 · about 10 minutes

async and await

Start slow work, keep going, and pick up the result when it's ready.

What you'll learn

  • Write async methods that return Task and Task<T>
  • Wait for a result with await
  • Run several tasks at once with Task.WhenAll

The volley

Through the smoke, the whole party attacks at once. Each adventurer's blow takes a moment to land, as many milliseconds as their power, and does that much damage. If they took turns, the dragon would have time to breathe fire between them, so every blow is started first and then the party waits for them all together: Bo strikes for 32, The volley lands: 97 damage and The dragon falls!, or The dragon flees deeper, with 32 HP when the party is too small. Starting slow work and waiting for it later is what async and await are for.

Waiting without blocking

Some work is slow because it waits: downloading a file, reading a database, calling a web API. An async method can pause at an await while it waits, and let other work run in the meantime.

  • async Task<int> Fetch() is a method that will produce an int later
  • await Fetch() waits for it and gives you the int
  • Task.Delay(100) is a pretend slow job: it just waits 100 milliseconds

An async method

Console.WriteLine("Asking for the score...");
int score = await GetScoreAsync("Ada");
Console.WriteLine($"Ada scored {score}");

static async Task<int> GetScoreAsync(string name)
{
    await Task.Delay(50);
    return name.Length * 100;
}

Output

Asking for the score...
Ada scored 300

Several at once

Calling an async method without await starts it and gives you a Task straight away. Start several, then await Task.WhenAll(...) to wait for them all; they run at the same time, so three 100 ms jobs take about 100 ms, not 300. The results come back in the order you listed the tasks.

Task.WhenAll

Task<int> a = SlowDouble(1);
Task<int> b = SlowDouble(2);
Task<int> c = SlowDouble(3);
int[] results = await Task.WhenAll(a, b, c);
Console.WriteLine(string.Join(" ", results));

static async Task<int> SlowDouble(int x)
{
    await Task.Delay(100);
    return x * 2;
}

Output

2 4 6

Every blow at once

party.Select(a => BlowAsync(a)).ToArray() calls BlowAsync for every adventurer without awaiting any of them, so all the blows have started before the next line runs. await Task.WhenAll(volley) then waits until the last one lands, which takes about as long as the strongest adventurer's blow rather than all of them added up, and gives back an int[] in the party's order, even though the weakest blow lands first. That's why landed[i] belongs to party[i]. The main code now uses await, so C# makes the whole program async for you; nothing else needs to change.

Tip

By convention, async method names end in Async, like GetScoreAsync, so callers know to await them.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.