Lesson 7 / 26

async and await

Write non-blocking code with Task, async and await and avoid the common deadlock traps.

Do not block a thread

While a request waits for a database or HTTP call, await frees the thread to serve other requests. The method resumes when the result is ready. This is how a small thread pool serves many users.

An async method

An async method returns Task<T>. Awaiting it gives the T. Task.Delay stands in for a slow call here.

static async Task<int> GetCountAsync()
{
    await Task.Delay(100);
    return 42;
}

var count = await GetCountAsync();
Console.WriteLine(count);

Output:

42

Never use .Result or .Wait()

Blocking on a task with .Result or .Wait() wastes a thread and can deadlock in some app types. Make the whole call chain async instead, and avoid async void except for event handlers.

Quick check: What should an async method that returns no value return?

  • void
  • int
  • Task
  • object
Answer

Task — Return `Task` so callers can await it and catch exceptions. `async void` hides failures.