Async Programming

Overview

Asynchronous programming enables responsive UI and efficient use of system resources by allowing operations to run without blocking the calling thread. Windows provides a rich set of APIs, including Task, async/await, and the thread pool, to simplify the creation of scalable, non‑blocking code.

Task Parallel Library (TPL)

The System.Threading.Tasks.Task type represents an asynchronous operation. Use Task.Run to offload CPU‑bound work to a thread pool thread.

Task.Run(() => {
    // CPU‑bound work
    ComputeHeavyData();
});

async / await

Mark a method with async and use await to asynchronously wait for a task without blocking.

public async Task<string> GetDataAsync()
{
    using var client = new HttpClient();
    var response = await client.GetStringAsync("https://api.example.com/data");
    return response;
}

ThreadPool API

The thread pool efficiently reuses threads for short‑lived work. You can queue work items with ThreadPool.QueueUserWorkItem or use the newer ThreadPool methods for async I/O.

ThreadPool.QueueUserWorkItem(state =>
{
    // Background work
    Process(state);
}, myState);

Common Patterns

  • Fire‑and‑forget with Task.Run for background processing.
  • Progress reporting using IProgress<T>.
  • Cancelling operations with CancellationToken.

Code Samples

Explore practical examples in the Samples section.