I am using Ef Core with ASP.NET Core to build up a database application.
IN ASP.NET Core, there is a build in CancellationToken: HttpContext.RequestAborted, which would trigger when the client abort the http connection.
At the same time, there is also a CancellationToken parameter for most of Ef Core Query API. I wonder whether it is best practice to pass HttpContext.RequestAborted everywhere for Ef Core Query, which is really more tedious and the code is mess up with HttpContext.RequestAborted
CodePudding user response:
Сreate a separate layer for accessing the database receiving cancellation token as a parameter of method and pass there HttpContext.Request Aborted from the web application layer. Then the code will look cleaner
You can create something like Repository with methods
GetSomething(parameters, СancellationToken)
And use it in controller passing HttpContext.RequestAborted
CodePudding user response:
I would consider it as good practice to pass the CancellationToken around. Without the CancellationToken your queries (or other async operations) will still run even if the client cancelled the request. So you might end up wasting resources for nothing.
However in some cases you don't want to cancel your operation. For example clean up code after an Exception.
So you need to decide from case to case.
