How to cancel a CancellationToken

46,993

Solution 1

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.

Solution 2

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.

Solution 3

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.

Solution 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?

Share:
46,993
Leonardo
Author by

Leonardo

Developer, Architect, Tech Lover!

Updated on October 28, 2021

Comments

  • Leonardo
    Leonardo over 2 years

    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?

  • RyanS
    RyanS almost 9 years
    @Leonardo, You should first create the tokensource and then request the token from it. Look at the example code in the link I provided
  • Der Kommissar
    Der Kommissar almost 9 years
    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.)
  • RyanS
    RyanS almost 9 years
    @Leonardo, If you are still confused after looking at the longer example update your question with your code and I will try to provide more information
  • Servy
    Servy almost 9 years
    @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.
  • Der Kommissar
    Der Kommissar almost 9 years
    @RyanS You should probably add something answering the how can I, in possession of ONLY a CancellationToken, cancel it? as well.
  • Machinarius
    Machinarius almost 9 years
    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.
  • RyanS
    RyanS almost 9 years
    @EBrown, From my understanding and as Servy commented that is not possible and is not the way to use Cancelation Token
  • Der Kommissar
    Der Kommissar almost 9 years
    @RyanS I meant you should add Servy's information (or mine) to the answer.
  • Sjeijoet
    Sjeijoet over 7 years
    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.
  • JobaDiniz
    JobaDiniz about 7 years
    @RyanS "When given a Token, you can create a new instance of token source assign it's token to the provided token and cancel it". This is not true, you cannot assign CancellationTokenSource.Token property, it is readonly.
  • RyanS
    RyanS about 7 years
    @JobaDiniz its been a while since I added this answer but I believe I meant that you could get the token from the tokensource and assign that to something else, not the other way around (which as you stated cannot be done)
  • Niels Filter
    Niels Filter about 5 years
    Ha, that's really clever! I know it's a hack, but then again, cancelling a token without a Source calls for a hack. Good work :)
  • pm.lemay
    pm.lemay almost 4 years
    Don't forget to call source.Dispose(); when you are done using it. stackoverflow.com/questions/6960520/…
  • Peter Mortensen
    Peter Mortensen almost 3 years
    Perhaps address the question directly? I take it the answer is "You can't"(?)
  • Theodor Zoulias
    Theodor Zoulias almost 3 years
    "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." <== Could you provide an example of this technique?