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
GetStringAsyncthe 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,
awaitpauses this method (without blocking the thread) until the operation completes, then resumes exactly where it left off. - A
Taskrepresents work that's in progress, possibly not finished yet.Task<T>is the same idea but the work eventually produces a value of typeT, likeDownloadAsyncreturningTask<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.