Lesson 47 +10 XP

Async & Await

Async & Await

Some operations - like web requests, file reads, and database calls - are slow. Async programming lets your program start them, do other work, and handle the result when it's ready, instead of freezing.

The problem with blocking

If you wait for a slow web request on the main thread, your app freezes. Async methods avoid this.

The async and await keywords

An async method returns a Task (or Task<T>) and uses await for slow operations:

using System.Threading.Tasks;

static async Task<string> DownloadAsync()
{
  await Task.Delay(1000);             // pretend to be slow
  return "data downloaded";
}

static async Task Main(string[] args)
{
  string result = await DownloadAsync();
  Console.WriteLine(result);
}

The rules

  • Mark a method async if it contains await.
  • async methods return Task (no result) or Task<T> (with result).
  • await pauses the method until the awaited task finishes - without blocking the whole app.
  • Main can be async Task to await top-level code.

Why it matters

The UI stays responsive, servers handle more requests, and long operations don't freeze your program.

Task.Run

Task.Run(() => ...) runs a chunk of work on a background thread:

await Task.Run(() => HeavyComputation());

TL;DR

  • async + await handle slow work without freezing.
  • async methods return Task or Task<T>.
  • await waits for the result, non-blocking.
  • Critical for web, file I/O, and responsive UIs.