๐Ÿ  VisualStudioTutor.com  ยท  C# Tutorial Home  ยท  C# Lesson 14 of 40
Lesson 14 of 40 Async Intermediate โฑ 40 min

Async / Await & Task-Based Programming

Write responsive, scalable applications with C#'s async/await โ€” understand Tasks, ConfigureAwait, cancellation, and common pitfalls.

Part 1: async and await Basics

// Mark method async, return Task or Task<T>
public async Task<string> FetchUserAsync(int id)
{
    var response = await _http.GetStringAsync($"/users/{id}");
    return response;
}

Part 2: Task.WhenAll & Task.WhenAny

// Run multiple tasks concurrently
var (user, orders) = await (
    FetchUserAsync(id),
    FetchOrdersAsync(id)
);

// Alternatively with Task.WhenAll
await Task.WhenAll(tasks);

// First to complete wins
var first = await Task.WhenAny(tasks);

Part 3: CancellationToken

public async Task<List<Order>> GetOrdersAsync(CancellationToken ct = default)
{
    ct.ThrowIfCancellationRequested();
    return await _db.Orders.ToListAsync(ct);
}

// With timeout
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await GetOrdersAsync(cts.Token);

Part 4: Common Async Mistakes

Anti-PatternWhy BadFix
.Result or .Wait()Deadlocks on UI/ASP threadsAlways await
async voidExceptions can't be caughtReturn Task
Missing ConfigureAwait(false)Unnecessary context switch in libsAdd it in library code
Forgetting cancellation tokenCan't cancel long operationsAccept and pass CancellationToken

C# in Visual Studio 2026

๐Ÿ“˜ This lesson is part of the book C# in Visual Studio 2026 by Dr. Liew Voon Kiong.

View on Amazon Kindle Edition