Good Code
The good version accepts a CancellationToken from the request and passes it into the service call. If the client disconnects, downstream work can stop.
Lesson 03
Thread cancellation tokens through async calls so abandoned requests can stop database, HTTP, or queue work.
public sealed class ReviewController
{
public async Task<IResult> GetAsync(
Guid id,
CancellationToken cancellationToken)
{
// Cancellation flows from the request into the service.
ReviewDto? review = await reviews.FindAsync(id, cancellationToken);
return review is null ? Results.NotFound() : Results.Ok(review);
}
}public sealed class ReviewController
{
public IResult Get(Guid id)
{
// Blocking on async work can tie up request threads.
ReviewDto? review = reviews.FindAsync(id).Result;
return review is null ? Results.NotFound() : Results.Ok(review);
}
}The good version accepts a CancellationToken from the request and passes it into the service call. If the client disconnects, downstream work can stop.
The bad version blocks on .Result, loses cancellation, and can exhaust request threads under load.
CancellationToken through every operation that can wait on I/O.