async / await
Keywords for defining and calling asynchronous methods. Use async to make a method asynchronous, and await to wait for an asynchronous operation to complete.
Syntax
// Define an async method (no return value)
async Task MethodName()
{
await asyncOperation;
}
// Define an async method (with return value)
async Task<T> MethodName()
{
T result = await asyncOperation;
return result;
}
// Call an async method
await MethodName();
T value = await MethodName();
Keywords and Types
| Keyword / Type | Description |
|---|---|
| async | Declares a method as asynchronous, enabling the use of await inside it. |
| await | Waits for an asynchronous operation to complete without blocking the thread, returning control to the caller. |
| Task | Represents an asynchronous operation with no return value. |
| Task<T> | Represents an asynchronous operation that returns a value of type T. |
| ValueTask<T> | A lightweight asynchronous type that reduces heap allocations, useful when the operation completes synchronously most of the time. |
| async void | An asynchronous method reserved for event handlers. Avoid it in general use, as exceptions cannot propagate to the caller. |
Sample Code
using System;
using System.Net.Http;
using System.Threading.Tasks;
// Define an async method with no return value.
async Task PrintGreetingAsync(string name)
{
await Task.Delay(100); // Simulates a 100ms delay.
Console.WriteLine($"Hello, {name}!");
}
// Define an async method with a return value.
async Task<int> AddAsync(int a, int b)
{
await Task.Delay(50); // Simulates an async operation.
return a + b;
}
// Run multiple async operations sequentially.
async Task RunSequentialAsync()
{
await PrintGreetingAsync("Alice");
await PrintGreetingAsync("Bob");
int result = await AddAsync(3, 4);
Console.WriteLine($"3 + 4 = {result}");
}
// Entry point (.NET 5 and later allow async Main)
await RunSequentialAsync();
Console.WriteLine("Done");
Notes
Using async/await lets you wait for time-consuming operations (such as network or file I/O) to complete without blocking the thread. At each await point, the thread is released and the remaining code resumes after the operation finishes.
Do not use async void outside of event handlers. Exceptions thrown inside an async void method cannot propagate to the caller, making them extremely difficult to debug. Always return async Task instead.
To run multiple async operations in parallel, see Task.Run() / Task.Delay() / Task.WhenAll(). For exception handling inside async methods, see Exception Handling and Async.
If you find any errors or copyright issues, please contact us.