If I have a CancellationTokenSource that is still in scope when I'm checking for cancellation -- e.g., if I've just made a database query and have not yet passed the CancellationToken down to Tasks to process the results -- should I access IsCancellationRequested from the source or from its token?
In other words, if both options are available, which is preferred, and why?
1:
myCancellationTokenSource.IsCancellationRequested
2:
myCancellationTokenSource.Token.IsCancellationRequested
Description: Asynchronous methods should take a CancellationToken. Sometimes, async methods are not written with cooperative cancellation in mind. Either because a developer is not aware of the pattern or because they consider it unnecessary in a specific case.
The CancellationTokenSource is the 'thing' that issues the cancellation, for whatever reason. It needs a way to 'dispatch' that cancellation to all the CancellationToken 's it has issued. That's how, for example, ASP.NET can cancel operations when a request is aborted.
Yes, you are supposed to call ThrowIfCancellationRequested() manually, in the appropriate places in your code (where appropriate is determined by you as a programmer). Consider the following example of a simple job processing function that reads jobs from a queue and does stuff with them.
In this particular scenario, I believe the two are essentially equivalent. I would prefer using the Token if only because this simplifies refactoring if you later split off the logic checking cancellation from the logic creating the cancellation source. To further that end, I would store the token in a local reference and use that reference for the checking.
Typically, myCancellationTokenSource
is used to initiate the cancellation (by a parent thread, for instance). myCancellationTokenSource.Token
is the associated CancellationToken
that you would pass to something like TaskFactory.StartNew()
. The task would then monitor the CancellationToken.IsCancellationRequested
to determine when to shut down.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With