c# · level 3 · unit 6 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Start every task first, then await them all together.
Awaiting tasks one by one means each waits for the last: three 100 ms lookups take 300 ms. Run them , all in flight at the same time, and the waits overlap, so the whole job takes about 100 ms.
Start each task without await and keep the tasks. Then . It finishes when the last one does and hands back an array of results in the order you started them, never the order they finished. That keeps your output the same on every run.
using System;
using System.Linq;
using System.Threading.Tasks;
string[] towns = { "Leeds", "Bath", "York" };
Task<string>[] lookups = towns.Select(LookupAsync).ToArray();
string[] reports = await Task.WhenAll(lookups);
foreach (string report in reports)
{
Console.WriteLine(report);
}
async Task<string> LookupAsync(string town)
{
await Task.Delay(town.Length * 40);
return $"{town}: {town.Length * 3} degrees";
} towns.Select(LookupAsync) passes the method itself, the same as town => LookupAsync(town).
guess first
The slowest starts first. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
using System.Linq;
using System.Threading.Tasks;
int[] delays = { 300, 100, 200 };
var tasks = delays.Select(async ms =>
{
await Task.Delay(ms);
return ms;
});
int[] finished = await Task.WhenAll(tasks);
Console.WriteLine(string.Join(" ", finished));
Console.WriteLine(finished.Sum());
your turn
Your turn. Look up the fruit prices.
Choose three fruits of your own on line 5. Then, on line 7, wait for every lookup at once.
output
press run to see what happens
fix it
The server is called too often. Can you fix it?
output
press run to see what happens
- Three names, but four server calls. When does
SelectcallFetchAsync? lookupsis a lazy query.WhenAllwalks it once, thenFirstwalks it again and starts a fresh task.- Add
.ToArray()afterSelect(FetchAsync)on line 7, so the tasks start once and are kept, then run.
nailed it
your tasks now run side by side. :D
- Start every task first, then
await Task.WhenAll. - Results come back in the order you started them.
- Keep tasks in an array, so a lazy query cannot restart them.
new words in your collection
- concurrently
- Task.WhenAll
This lesson isn’t saved. A free account remembers every lesson you finish.