How to cancel a CancellationToken

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.

Leave a Comment

404 Not Found

Not Found

The requested URL was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.