Async Intro
Mark async methods
An async method returns Task or Task<T> and may await other tasks.
async Task<string> LoadAsync()
{
await Task.Delay(50);
return "done";
}
Console.WriteLine(await LoadAsync());
Why await helps
Await frees the thread while waiting on I/O so apps stay responsive. CPU-heavy work still needs care.
Handle faults
Exceptions from awaited tasks surface at the await point.
try
{
await LoadAsync();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Async tips
- Prefer async all the way up to the entry point
- Avoid
.Resultand.Wait()in app code—they can deadlock - Name async methods with an
Asyncsuffix by convention - Start with
HttpClientand file APIs when practicing
Comments
One comment per signed-in account. Comments are saved with this page’s URL.