Core Features
Async/Await
Write non-blocking code with C#'s async/await pattern for responsive applications.
Why Async?
Synchronous code blocks the thread while waiting for I/O (disk, network, database). Async code releases the thread to do other work while waiting.
async/await Keywords
async: Marks a method as asynchronousawait: Suspends execution until the awaited task completesTask: Represents an ongoing operation (likePromisein JS)Task<T>: Async operation that returns a value
Best Practices
- Return
TaskorTask<T>(notvoid) from async methods - Use
awaitinstead of.Result(avoids deadlocks) - Use
Task.WhenAllfor parallel operations - Suffix async methods with
Async
Example
csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Collections.Generic;
public class WeatherService {
private readonly HttpClient _client;
public WeatherService(HttpClient client) {
_client = client;
}
// Async method returns Task<string>
public async Task<string> GetWeatherAsync(string city) {
string url = $"https://api.weather.com/{city}";
string response = await _client.GetStringAsync(url);
return response;
}
// Multiple async operations in sequence
public async Task<(string, string)> GetTwoCitiesAsync() {
string london = await GetWeatherAsync("london");
string paris = await GetWeatherAsync("paris");
return (london, paris);
}
// Parallel async operations (faster!)
public async Task<string[]> GetMultipleCitiesAsync(string[] cities) {
Task<string>[] tasks = Array.ConvertAll(cities, GetWeatherAsync);
return await Task.WhenAll(tasks);
}
}
// Error handling
public async Task<bool> TrySaveDataAsync(string data) {
try {
await SaveToFileAsync(data);
await NotifyApiAsync(data);
return true;
} catch (HttpRequestException ex) {
Console.WriteLine($"Network error: {ex.Message}");
return false;
} catch (Exception ex) {
Console.WriteLine($"Error: {ex.Message}");
return false;
}
}
// Cancellation token for timeout/cancel support
public async Task<string> GetDataWithTimeoutAsync(
CancellationToken cancellationToken = default) {
using var client = new HttpClient();
string result = await client
.GetStringAsync("https://api.example.com/data", cancellationToken);
return result;
}
// Entry point
async Task Main() {
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
try {
// await GetDataWithTimeoutAsync(cts.Token);
Console.WriteLine("Done!");
} catch (OperationCanceledException) {
Console.WriteLine("Timed out!");
}
}Try it yourself — CSHARP