Async/Await Programming
Master asynchronous programming with async/await for responsive applications. This is a foundational concept in Microsoft application framework that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world .NET experience. Take your time with each section and practice the examples
Understanding Async/Await
Async/await allows you to write asynchronous code that looks like synchronous code. It helps prevent blocking operations and improves application responsiveness.. This is an essential concept that every .NET developer must understand thoroughly. In professional development environments, getting this right can mean the difference between code that works reliably and code that breaks in production. The following sections break this down into clear, digestible pieces with practical examples you can try immediately
Async Methods and Tasks
// Async method example
public async Task<string> FetchDataAsync(string url)
{
using (HttpClient client = new HttpClient())
{
try
{
string result = await client.GetStringAsync(url);
return result;
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Error fetching data: {ex.Message}");
return null;
}
}
}
// Multiple async operations
public async Task<List<string>> FetchMultipleDataAsync(List<string> urls)
{
var tasks = urls.Select(url => FetchDataAsync(url));
var results = await Task.WhenAll(tasks);
return results.Where(r => r != null).ToList();
}
// Async with cancellation
public async Task<string> FetchDataWithCancellationAsync(string url, CancellationToken cancellationToken)
{
using (HttpClient client = new HttpClient())
{
try
{
string result = await client.GetStringAsync(url, cancellationToken);
return result;
}
catch (OperationCanceledException)
{
Console.WriteLine("Operation was cancelled");
return null;
}
}
}
// Usage
async Task Main()
{
string data = await FetchDataAsync("https://api.example.com/data");
Console.WriteLine(data);
var urls = new List<string> { "url1", "url2", "url3" };
var results = await FetchMultipleDataAsync(urls);
Console.WriteLine($"Fetched {results.Count} items");
}