92

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?

3
  • 1
    You're looking for CancellationTokenSource msdn.microsoft.com/en-us/library/… Jun 16, 2015 at 18:26
  • 1
    @CoderDennis I dont see how i can obtain the token source given only the token...
    – Leonardo
    Jun 16, 2015 at 18:29
  • 2
    If you don't have a CancellationTokenSource then you can't cancel it. The token is an object that all the threads share, this object is set by the CancellationTokenSource.Cancel() method. Once done so, the CancellationToken.IsCancellationRequested would be true. Until then, it will always be false. (It cannot be set directly.) If you don't have a CancellationTokenSource, then there is nothing that is capable of throwing the cancellation. You require a CancellationTokenSource to cancel threads like that. Jun 16, 2015 at 18:43

4 Answers 4

123

As the documentation states, you need to call the Cancel() method from the token source, not the token itself. Note the example code in the CancellationToken Struct documentation:

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

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

Without a reference to the source you cannot cancel the token, this is by design.

As a flawed workaround, when given a CancellationToken, you can create a new instance of the token source, assign its token to the provided token, and cancel the new source:

// Define the cancellation token.
CancellationTokenSource newSource = new CancellationTokenSource();
existingToken = newSource.Token;
...
newSource.Cancel();
// "existingToken" is cancelled hereafter

...but this will only affect downstream consumers of the token. Any entities with the token prior to updating the reference will still have the original, uncancelled token.

But do note that if you're creating the token to track tasks, then you do have the source, so this shouldn't be an issue.

14
  • 1
    @Leonardo, You should first create the tokensource and then request the token from it. Look at the example code in the link I provided
    – RyanS
    Jun 16, 2015 at 18:32
  • 1
    This is the method I use for our backup utility at work - if any Task fails my results are useless as well. (The two databases, one SQL, one AS/400 DB2, are out of sync, and that's unacceptable. So I discard all data if anything fails.) Jun 16, 2015 at 18:34
  • 6
    @Leonardo You can't get the source when given only the token. it is by design that you cannot cancel a token when all you have is that token. It would be a broken system if it could.
    – Servy
    Jun 16, 2015 at 18:41
  • 1
    @RyanS I meant you should add Servy's information (or mine) to the answer. Jun 16, 2015 at 19:24
  • 3
    Overriding previouslyProvidedToken like in the edit is a bad practice... If the source of the provided token is cancelled (on a higher level in the tree), this functionally would not react to that cancel. Passing a CancellationToken would be entirely useless in this case, so Daniel Park's answer offers a better solution.
    – Sjeijoet
    Sep 19, 2016 at 8:40
23

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.

0
13

A token gives you the right to know someone is trying to cancel something. It does not give you the right to actually signal a cancellation. Only the cancellation token source gives you that. This is by design.

1
  • 1
    Perhaps address the question directly? I take it the answer is "You can't"(?) May 12, 2021 at 20:23
4

Spawn CancellationToken instances from a CancellationTokenSource instance and call Cancel on the CTS instance.

Example: Cancel()

There's also a way to gracefully cancel threads without them firing exceptions. Just check the CT for IsCancellationRequested and handle the case yourself.

More information: Use of IsCancellationRequested property?

1
  • 2
    Then as you are being provided one you are in control of the cancellation. You can either keep tabs on IsCancellationRequested or rely on the framework throwing an exception on your thread to forcibly do so. Jun 16, 2015 at 18:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.