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

Lesson 1 of 7

Introduction to Asynchronous Programming

Some operations, reading a file, calling a web API, querying a database, take real time to complete, and don't need the CPU while they wait. Asynchronous code lets your program keep doing other work during that wait, instead of blocking a thread that's doing nothing but sitting idle.

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        Console.WriteLine("Starting download...");
        string content = await DownloadAsync("https://example.com");
        Console.WriteLine($"Downloaded {content.Length} characters");
    }

    static async Task<string> DownloadAsync(string url)
    {
        using var client = new HttpClient();
        return await client.GetStringAsync(url);
    }
}

Synchronous vs asynchronous

  • Synchronous code blocks: calling GetStringAsync the old-fashioned, blocking way would leave the thread sitting frozen, doing nothing, until the network response arrives.
  • Asynchronous code frees the thread during the wait, await pauses this method (without blocking the thread) until the operation completes, then resumes exactly where it left off.
  • A Task represents work that's in progress, possibly not finished yet. Task<T> is the same idea but the work eventually produces a value of type T, like DownloadAsync returning Task<string>.

Why it matters

In a desktop or mobile app, blocking the main thread freezes the UI, buttons stop responding, the window stops redrawing. On a server, one thread blocked waiting on a database call is one fewer thread available to handle other requests. Async code avoids both problems by giving the thread back while waiting.

📝 Async Basics Quiz

Passing score: 70%
  1. 1.What does await do to the method it is used in?

  2. 2.A ____<T> represents asynchronous work that will eventually produce a value of type T.

  3. 3.Blocking the main thread in a desktop app can freeze the UI.