How to use async and await in C#
The async and await keywords in C# enable asynchronous programming. An async method can contain await expressions that suspend execution until an awaited task completes, allowing other work to proceed.
Methods marked with async typically return Task or Task<T>. The await keyword unwraps the result from a task without blocking the calling thread.
Async methods should have "Async" suffix by convention (e.g., GetDataAsync), and you should avoid async void except for event handlers.
C# Example Code
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class AsyncAwaitBasics
{
public static async Task Main(string[] args)
{
Console.WriteLine("Starting async operation...");
// Call async method with await
string result = await FetchDataAsync();
Console.WriteLine($"Result: {result}");
// Multiple async calls in sequence
await Task.Delay(1000); // Wait 1 second
Console.WriteLine("One second passed");
// Running multiple tasks concurrently
Task<int> task1 = CalculateAsync(5);
Task<int> task2 = CalculateAsync(10);
int[] results = await Task.WhenAll(task1, task2);
Console.WriteLine($"Results: {results[0]}, {results[1]}");
Console.WriteLine("All operations completed!");
}
static async Task<string> FetchDataAsync()
{
// Simulate async operation
await Task.Delay(500);
return "Data fetched successfully";
}
static async Task<int> CalculateAsync(int value)
{
await Task.Delay(200);
return value * 2;
}
// Example with HttpClient
static async Task<string> GetWebContentAsync(string url)
{
using HttpClient client = new HttpClient();
string content = await client.GetStringAsync(url);
return content;
}
}