c# · level 3 · unit 6 · lesson 1
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
The kettle goes on. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
using System.Threading.Tasks;
Console.WriteLine("1. kettle on");
Task<string> tea = MakeTeaAsync();
Console.WriteLine("2. find a biscuit");
Console.WriteLine(await tea);
async Task<string> MakeTeaAsync()
{
Console.WriteLine("3. water heating");
await Task.Delay(100);
return "4. tea is ready";
}
your turn
Your turn. Wait for the price.
On line 4, wait for the price to arrive, so price holds a number, not a promise. Then choose your own product name.
output
press run to see what happens
fix it
The weather app will not compile. Can you fix it?
output
press run to see what happens
- C# cannot turn a
Task<string>into astringon line 4. - A
Task<string>is a promise of text, not the text itself. Something must wait for it. - Put
awaitbeforeForecastAsync("Leeds")on line 4, then run.
nailed it
your code can wait without freezing. :D
- An
asyncmethod returns aTask<T>, a promise of a result. awaitpauses until the task finishes, then gives the result.- Without
await, you hold the promise, not the answer.
new words in your collection
- asynchronous
- Task
- await
This lesson isn’t saved. A free account remembers every lesson you finish.