Loading lessons...
Async & Await
Async & Await
Some operations - like web requests, file reads, and database calls - are slow. Async programming lets your program start them, do other work, and handle the result when it's ready, instead of freezing.
The problem with blocking
If you wait for a slow web request on the main thread, your app freezes. Async methods avoid this.
The async and await keywords
An async method returns a Task (or Task<T>) and uses await for slow operations:
using System.Threading.Tasks;
static async Task<string> DownloadAsync()
{
await Task.Delay(1000); // pretend to be slow
return "data downloaded";
}
static async Task Main(string[] args)
{
string result = await DownloadAsync();
Console.WriteLine(result);
}
The rules
- Mark a method
asyncif it containsawait. asyncmethods returnTask(no result) orTask<T>(with result).awaitpauses the method until the awaited task finishes - without blocking the whole app.Maincan beasync Taskto await top-level code.
Why it matters
The UI stays responsive, servers handle more requests, and long operations don't freeze your program.
Task.Run
Task.Run(() => ...) runs a chunk of work on a background thread:
await Task.Run(() => HeavyComputation());
TL;DR
async+awaithandle slow work without freezing.asyncmethods returnTaskorTask<T>.awaitwaits for the result, non-blocking.- Critical for web, file I/O, and responsive UIs.