Async & Await in C#
Non-blocking code. Keep UI responsive. Scale servers without threads.
60-Second Version:
async marks a method that can pause. await pauses without blocking threads. Think of Kunal ordering pizza while watching TV.1. Why Async? Threads Are Expensive
Kunal orders pizza. Sync way: stand at door 30 mins, doing nothing. Thread blocked. Async way: order, set timer, watch TV. When bell rings, pause TV, get pizza, resume. Thread was free to do other work.
// Sync: blocks thread for 30 mins
void OrderSync() {
Pizza p = PizzaService.Order(); // Thread waits here
Eat(p);
}
// Async: thread released during wait
async Task OrderAsync() {
Pizza p = await PizzaService.OrderAsync(); // Thread goes do other stuff
Eat(p); // Resumes when pizza ready
}
2. await = "Come Back Later"
await doesn't start work. It waits for work that's already running. If Prerna calls await DownloadAsync(), the download starts, then her method returns a Task to caller.
3. Task vs void: Never async void
async Task = awaitable. async void = fire-and-forget. You can't catch exceptions from async void. Only use for event handlers.
public async Task SaveAsync() { } // Good
public async void Button_Click() { } // Only for events
Beginner Trap: Kaushal writes
var data = GetDataAsync().Result; in ASP.NET. Deadlock. Fix: await all the way. If you must block, use .GetAwaiter().GetResult() but avoid it.
No comments yet. Be the first to share your thoughts!