Async Intro

View saved

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 .Result and .Wait() in app code—they can deadlock
  • Name async methods with an Async suffix by convention
  • Start with HttpClient and file APIs when practicing

Comments

One comment per signed-in account. Comments are saved with this page’s URL.