C# async and await
async and await let a program wait for slow work (a web request, a file) without freezing. A method marked async returns a Task. Here two tasks run, and their results are collected in a fixed order so the output is predictable.
ExampleC#
using System;
using System.Threading.Tasks;
class Program
{
static async Task<int> SlowSquareAsync(int n)
{
await Task.Delay(50);
return n * n;
}
static async Task Main()
{
Task<int> a = SlowSquareAsync(3);
Task<int> b = SlowSquareAsync(4);
int[] results = await Task.WhenAll(a, b);
Console.WriteLine(results[0] + " " + results[1]);
int single = await SlowSquareAsync(5);
Console.WriteLine(single);
}
}Output
9 16 25
Quick check
What does await do?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.