Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel a CancellationToken

I start a task, that starts other tasks and so forth. Given that tree, if any task fails the result of the whole operation is useless. I'm considering using cancellation tokens. To my surprise, the token does not have a "CancelThisToken()" method...

How can I, in possession of only a CancellationToken, cancel it?

like image 737
Leonardo Avatar asked Jun 16 '15 18:06

Leonardo


People also ask

How do I cancel a CancellationToken?

A CancellationToken can only be created by creating a new instance of CancellationTokenSource . CancellationToken is immutable and must be canceled by calling CancellationTokenSource. cancel() on the CancellationTokenSource that creates it. It can only be canceled once.

Does disposing a CancellationTokenSource cancel it?

The Dispose method leaves the CancellationTokenSource in an unusable state. After calling Dispose , you must release all references to the CancellationTokenSource so the garbage collector can reclaim the memory that the CancellationTokenSource was occupying.

How do I cancel async tasks?

You can cancel an asynchronous operation after a period of time by using the CancellationTokenSource. CancelAfter method if you don't want to wait for the operation to finish.


2 Answers

As the documentation state, you need to call the cancel method from the source object. Example code is included in the link you provided. Here are the relevant sections:

// Define the cancellation token. CancellationTokenSource source = new CancellationTokenSource(); previouslyProvidedToken = source.Token; ... source.Cancel(); 

CancellationToken Struct

how can I, in possession of only a CancellationToken, cancel it?

Edit: I wrote this years ago and revisiting it I don't know if its actually valid either when written or right now. Leaving it here as-is for posterity.

Without a reference to the source you cannot cancel a token. That doesn't mean that you need the CancellationTokenSource that first spawned the token. When given a CancellationToken, you can create a new instance of the token source, assign it's token to the provided token, and cancel it. All other parties that can read this token will see that it's cancellation has been requested.

like image 82
RyanS Avatar answered Oct 08 '22 04:10

RyanS


As an extension of the answers provided so far, if you want to have both a CancellationToken instance provided to your methods, and cancel internally, you should examine CancellationTokenSource.CreateLinkedTokenSource. In essence this will cancel either when cts.Cancel() is called, or one of its supplied tokens is.

like image 27
Daniel Park Avatar answered Oct 08 '22 03:10

Daniel Park