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?
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: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:...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.