async, await, and CancellationTokenThe required CancellationToken
No narration yet
Module 7 · Lesson 211 min

The required CancellationToken

A CancellationToken is how a caller says "stop, the client hung up" or "the deadline passed." ASP.NET hands one to your endpoint per request; you thread it down through every async IO call so a cancelled request stops doing work instead of finishing pointlessly. TS has AbortSignal; this is the same idea, taken seriously.

Threading the token (the target shape)
// Required parameter, no default, passed down to the IO call.
public async Task<IReadOnlyList<DecidedSnapshot>> GetFlightDecisions(
    IEnumerable<string> flightNumbers, CancellationToken cancellationToken)
{
    return await _dbContext.FlightDisruptionCostCalcs
        .Where(x => x.DecidedAtUtc != null)
        .ToListAsync(cancellationToken);   // token flows into EF's IO
}
Practice

Try it yourself

Recall

The CancellationToken rule

State the rule the way a reviewer holds it.

You're adding a new async repository method that queries the database. What must its signature include, and what must you NOT do to the token parameter?