×

c# · level 3 · unit 6 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

waits for slow work without freezing everything.

Real programs wait a lot: for a database, a file, a web server. code starts that slow work and lets the computer get on with other things until the answer is ready, instead of standing still.

A method marked async may use await, and it returns a : a promise of a T that arrives later. await pauses the method until the Task finishes, then hands over the result. Task.Delay(100) is a pretend slow job that finishes after 100 milliseconds.

The method runs normally until its first await. Top-level code can await too, and by habit async method names end in Async.

using System;
using System.Threading.Tasks;

Console.WriteLine("Ordering...");
string pizza = await CookAsync("margherita");
Console.WriteLine(pizza);
int minutes = await DeliveryTimeAsync();
Console.WriteLine($"Arrives in {minutes} minutes");

async Task<string> CookAsync(string name)
{
    await Task.Delay(100);
    return $"Hot {name} is ready";
}

async Task<int> DeliveryTimeAsync()
{
    await Task.Delay(50);
    return 25;
}

A method with nothing to return is async Task, and you await it the same way.