C# Async & Await
Asynchronous programming lets your program perform long-running operations, like network calls or file access, without blocking the main thread. C# uses the async and await keywords to write asynchronous code that reads like normal sequential code.
An async method returns a Task or Task<T>, and the await keyword pauses execution of that method until the awaited operation completes, without blocking other work.
async Task<T> MethodName() {
var result = await SomeAsyncCall();
return result;
}async and await keywords
Marking a method with `async` allows it to use `await` inside. await pauses the method until the awaited Task finishes, freeing up the thread to do other work in the meantime.
Task and Task<T>
An async method that doesn't return a value uses `Task` as its return type; one that returns a value uses `Task<T>`. Task.Delay() simulates a time-consuming asynchronous operation.
using System;
using System.Threading.Tasks;
class Program {
static async Task<int> GetNumberAsync() {
await Task.Delay(100);
return 42;
}
static async Task Main() {
int result = await GetNumberAsync();
Console.WriteLine(result);
}
}42Main awaits GetNumberAsync(), which pauses briefly before returning 42.
using System;
using System.Threading.Tasks;
class Program {
static async Task PrintAfterDelay(string message) {
await Task.Delay(50);
Console.WriteLine(message);
}
static async Task Main() {
Console.WriteLine("Start");
await PrintAfterDelay("Finished");
}
}Start
FinishedStart prints immediately, then after the awaited delay, Finished prints.
Key points
- async marks a method as asynchronous, enabling the use of await.
- await pauses a method until the awaited Task completes.
- Async methods return Task or Task<T>.
- Async programming avoids blocking the main thread during long operations.
