C# ยท Chapter 45 of 46

C# Async & Await

Asynchronous programming lets your program perform long-running operations, like network calls or file access, without blocking the main thread. C# uses the async and await keywords to write asynchronous code that reads like normal sequential code.

An async method returns a Task or Task<T>, and the await keyword pauses execution of that method until the awaited operation completes, without blocking other work.

Syntax
async Task<T> MethodName() {
  var result = await SomeAsyncCall();
  return result;
}

async and await keywords

Marking a method with `async` allows it to use `await` inside. await pauses the method until the awaited Task finishes, freeing up the thread to do other work in the meantime.

Task and Task<T>

An async method that doesn't return a value uses `Task` as its return type; one that returns a value uses `Task<T>`. Task.Delay() simulates a time-consuming asynchronous operation.

Example 1 (csharp)
using System;
using System.Threading.Tasks;

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

  static async Task Main() {
    int result = await GetNumberAsync();
    Console.WriteLine(result);
  }
}
Output
42

Main awaits GetNumberAsync(), which pauses briefly before returning 42.

Example 2 (csharp)
using System;
using System.Threading.Tasks;

class Program {
  static async Task PrintAfterDelay(string message) {
    await Task.Delay(50);
    Console.WriteLine(message);
  }

  static async Task Main() {
    Console.WriteLine("Start");
    await PrintAfterDelay("Finished");
  }
}
Output
Start
Finished

Start prints immediately, then after the awaited delay, Finished prints.

Key points

  • async marks a method as asynchronous, enabling the use of await.
  • await pauses a method until the awaited Task completes.
  • Async methods return Task or Task<T>.
  • Async programming avoids blocking the main thread during long operations.
๐Ÿ’ก Note: Async/await is especially important for I/O-bound work like web requests, database calls, and file access.

๐Ÿ“ Quick Quiz

1. What keyword marks a method as asynchronous?

2. What does await do?

3. What return type does an async method that returns an int use?