async and await
The async and await keywords are what actually let you write asynchronous code that reads like ordinary, top-to-bottom synchronous code.
using System;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
int result = await AddAsync(3, 4);
Console.WriteLine(result); // 7
}
static async Task<int> AddAsync(int a, int b)
{
await Task.Delay(1000); // simulate work
return a + b;
}
}
The rules
asyncmarks a method as containingawaitexpressions, it doesn't make the method run on a background thread by itself, it just enables theawaitkeyword inside it.- An
asyncmethod's return type is almost alwaysTask,Task<T>, or (rarely, for event handlers only)void. Never writeasync voidfor a regular method, exceptions thrown inside it can't be caught by the caller. awaitcan only be used inside a method markedasync, it unwraps aTask<T>into itsTresult (or just waits for a plainTaskto finish), and lets other work happen on the thread while waiting.Task.Delay(1000)asynchronously waits about a second without blocking the thread, unlikeThread.Sleep(1000), which does block it.
What "async all the way" means
Once one method needs to await something, every method that calls it should usually become async too, and its callers await it. Calling .Result or .Wait() on a Task to force synchronous behavior defeats the purpose and can even deadlock in UI applications, prefer await end to end.