How to cancel a CancellationToken

C#Task Parallel-LibraryCancellationtokensource

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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 - C#

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 - C#

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 - C#

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: https://stackoverflow.com/questions/15038529/use-of-iscancellationrequested-property

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLeonardoView Question on Stackoverflow
Solution 1 - C#RyanSView Answer on Stackoverflow
Solution 2 - C#Daniel ParkView Answer on Stackoverflow
Solution 3 - C#andrew pateView Answer on Stackoverflow
Solution 4 - C#MachinariusView Answer on Stackoverflow