async, await, and CancellationTokenTask, await, and never blocking
No narration yet
Module 7 · Lesson 114 min

Task, await, and never blocking

The easy half first. Task<T> is Promise<T>. await is await. An async method returns a Task, and you await it to get the value. If you've written async TS, you can read async C# immediately.

Async C#, Promise-shaped
public async Task<FlightRevertSummary?> LoadRevertSummary(string key)
{
    var rows = await _dbContext.FlightDisruptionCostCalcs
        .Where(x => x.EjdpUniqueFlightKey == key)
        .ToListAsync();
    return rows.Count == 0 ? null : Map(rows);
}

Now the half that gets PRs sent back. In C# you can block on a task: .Result, .Wait(), .GetAwaiter().GetResult(). These turn an async call into a synchronous one. They are almost always wrong. Blocking holds a thread-pool thread for the entire IO, which starves the pool under load, can deadlock, and throws away cancellation. There is no .Result in JS because the language won't let you; C# lets you, and you must not.

The wrong way and the right way
// Wrong: blocks a thread for the whole IO, discards cancellation, can deadlock.
var summary = _repo.LoadRevertSummary(key).Result;

// Right: await it, and make THIS method async too. Async is contagious; let it spread.
var summary = await _repo.LoadRevertSummary(key);
Practice

Try it yourself

Quiz

Spot the sync-over-async

Which line is the anti-pattern-#36 slop a Fusion reviewer will reject?