I am currently working on a .NET 8 Web API project consisting of multiple controllers. In my current setup, I’m passing a CancellationToken from the controller action methods down to the repository tier to manage asynchronous tasks.
However, after reading a recent Microsoft article: https://learn.microsoft.com/en-us/aspnet/core/performance/timeouts?view=aspnetcore-8.0 on implementing request timeouts in .NET 8, I came across a new concept. The article mentioned that when a timeout limit is reached, a CancellationToken found in HttpContext.RequestAborted has its IsCancellationRequested property set to true.
This has led me to wonder about the differences between using CancellationToken and HttpContext.RequestAborted.
Specifically, I would appreciate it if someone could clarify the following questions:
- What is the key difference between using CancellationToken passed down from my controller actions and using HttpContext.RequestAborted?
- In what scenarios would one be preferred over the other? Are there specific advantages or disadvantages associated with each one?
- If I were to implement HttpContext.RequestAborted, would I need to replace all instances of CancellationToken in my code, or can the two coexist and be used interchangeably?
Any insights or resources you could provide to help me better understand these concepts would be greatly appreciated.