Async & CancellationToken

Stop blocking threads. Cancel wasted work. Scale to 10,000 users.

The Problem: 1000 users hit GET /api/restaurants. Your code does _db.Restaurants.ToList(). Each call blocks a thread for 200ms. Server has 200 threads. 1000 users = 800 users waiting. Site freezes. 503 Service Unavailable.

1. The Zomato Kitchen Analogy

Sync = 1 Cook, 1 Order: Cook takes order โ†’ waits at oven 10 mins โ†’ can't take new orders. 5 orders = 50 min wait.

Async = 1 Cook, 10 Orders: Cook puts pizza in oven โ†’ sets timer โ†’ takes next order. Oven works while cook works. 5 orders = 12 mins. Cook never idle.

Thread = Cook. DB call = Oven. Async = Don't block cook while waiting for oven.

2. Fix It: async/await + ToListAsync

Bad - Blocks Thread:

[HttpGet]
public IActionResult Get() {
  var data = _db.Restaurants.ToList(); // Thread BLOCKED 200ms waiting for DB
  return Ok(data);
}

Good - Releases Thread:

[HttpGet]
public async Task Get() {
  var data = await _db.Restaurants.ToListAsync(); // Thread RELEASED. Handles other requests.
  return Ok(data); // Thread comes back when DB done
}

Result: 200 threads can now handle 10,000 requests. Because threads aren't blocked waiting.

3. CancellationToken - Stop Wasted Work

Problem: User searches restaurants โ†’ Waits 2 sec โ†’ Closes browser. Your API keeps hitting DB for 10 more sec. Wasted CPU, DB connections.

Fix: Accept CancellationToken. ASP.NET auto-cancels when client disconnects.

[HttpGet]
public async Task Search(string q, CancellationToken ct) {
  // Pass token to every async call
  var data = await _db.Restaurants
  .Where(r => r.Name.Contains(q))
  .ToListAsync(ct); // Throws OperationCanceledException if user cancels

  return Ok(data);
}

Test: Start request in Postman โ†’ Cancel โ†’ Check logs. See OperationCanceledException. DB query stopped. Server saved.

3 Rules of Async:
1. async all the way: Controller โ†’ Service โ†’ Repo โ†’ DB. If 1 method is sync, you lose benefit.
2. Never .Result or .Wait(): Causes deadlocks. Always await.
3. Always pass CancellationToken: From controller down to DB. HttpClient, EF Core, all support it.
Career-Killer Mistake: async void in controllers or services.
public async void ProcessOrder() { await _db.SaveChangesAsync(); }
Result: Exceptions crash entire app. Can't await. Can't catch. Fire-and-forget = fire-and-crash.
Fix: Always async Task. Only async void for event handlers like button clicks.

Quick Check ๐Ÿง 

Async mastered. Next: Entity Framework Core - The ORM that replaces SQL strings with C# LINQ. Query like: _db.Restaurants.Where(r => r.Rating > 4). This is the final core backend skill. Continue โ†’

Comments on Async & CancellationToken (0)

No comments yet. Be the first to share your thoughts!