C# Async Programming: Task, async/await & Cancellation

Lesson 2 of 7

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

  • async marks a method as containing await expressions, it doesn't make the method run on a background thread by itself, it just enables the await keyword inside it.
  • An async method's return type is almost always Task, Task<T>, or (rarely, for event handlers only) void. Never write async void for a regular method, exceptions thrown inside it can't be caught by the caller.
  • await can only be used inside a method marked async, it unwraps a Task<T> into its T result (or just waits for a plain Task to finish), and lets other work happen on the thread while waiting.
  • Task.Delay(1000) asynchronously waits about a second without blocking the thread, unlike Thread.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.

📝 async/await Quiz

Passing score: 70%
  1. 1.What does marking a method async actually do?

  2. 2.Task.____(1000) asynchronously waits about a second without blocking the thread, unlike Thread.Sleep.

  3. 3.Calling .Result on a Task instead of awaiting it can cause a deadlock in some applications.