async/await lets you write asynchronous code that looks like synchronous code — no callbacks, no manual thread management.
public static async Task<string> FetchDataAsync(string url)
{
using var client = new HttpClient();
string data = await client.GetStringAsync(url);
return data;
}
// Call it
string result = await FetchDataAsync("https://api.example.com/data");
Console.WriteLine(result);
// async Task — preferred: awaitable, exceptions propagate
public async Task DoWorkAsync()
{
await Task.Delay(1000); // simulates async work
Console.WriteLine("Work done.");
}
// async void — only for event handlers!
private async void Button_Click(object sender, EventArgs e)
{
await DoWorkAsync();
}
public static async Task RunParallelAsync()
{
Task<int> t1 = Task.Run(() => { Thread.Sleep(1000); return 1; });
Task<int> t2 = Task.Run(() => { Thread.Sleep(1000); return 2; });
Task<int> t3 = Task.Run(() => { Thread.Sleep(1000); return 3; });
// All three run concurrently — total time ~1 sec, not 3
int[] results = await Task.WhenAll(t1, t2, t3);
Console.WriteLine(results.Sum()); // 6
}
public static async Task LongOperationAsync(CancellationToken ct)
{
for (int i = 0; i < 100; i++)
{
ct.ThrowIfCancellationRequested();
await Task.Delay(100, ct);
Console.WriteLine($"Step {i}");
}
}
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3));
try
{
await LongOperationAsync(cts.Token);
}
catch (OperationCanceledException)
{
Console.WriteLine("Cancelled after 3 seconds.");
}