C#

Lesson 03

Async await and cancellation

Thread cancellation tokens through async calls so abandoned requests can stop database, HTTP, or queue work.

Good Code

src/ReviewController.cs
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);
    }
}

Bad Code

ReviewController.cs
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);
    }
}

Review Notes

What to review

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.

Bad Code

The bad version blocks on .Result, loses cancellation, and can exhaust request threads under load.

Takeaways

  • Async C# code should carry CancellationToken through every operation that can wait on I/O.