Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use IsCancellationRequested from token or source when both are available?

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
like image 284
Calvin Fisher Avatar asked May 06 '11 14:05

Calvin Fisher


People also ask

Should all async methods have cancellation token?

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.

What is difference between CancellationTokenSource and CancellationToken?

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.

Should I call ThrowIfCancellationRequested?

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.


2 Answers

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.

like image 154
Dan Bryant Avatar answered Nov 15 '22 23:11

Dan Bryant


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.

like image 43
seairth Avatar answered Nov 15 '22 21:11

seairth