1

So the IsCancellationRequested property of the CancellationToken is always true, even after declaring it as a variable and checking the token whether it was cancelled or not directly and it's infuriating me

how can I run a task if the token is already canceled?

qckmini6
  • 124
  • 2
  • 14
  • As a best practice, you should just ignore this property anyway and not have business logic react to any value it may have for **serious reasons**. _"[As a warning: replacing ThrowIfCancellationRequested with a bunch of checks for IsCancellationRequested exits gracefully, .... But that's not just an implementation detail; that affects observable behavior: the task will no longer end in the cancelled state, .... And that can affect not just explicit state checks, but also, more subtly, task chaining...](https://stackoverflow.com/questions/7343211/cancelling-a-task-is-throwing-an-exception)"_ –  Oct 29 '18 at 00:11
  • ...simply use `ThrowIfCancellationRequested()` –  Oct 29 '18 at 00:12

1 Answers1

1

The IsCancellationRequested will only be true if cancellation has been requested (public or not)

Gets whether cancellation has been requested for this CancellationTokenSource.

Remarks

This property indicates whether cancellation has been requested for this token source, such as due to a call to its Cancel method.

If this property returns true, it only guarantees that cancellation has been requested. It does not guarantee that every handler registered with the corresponding token has finished executing, nor that cancellation requests have finished propagating to all registered handlers. Additional synchronization may be required, particularly in situations where related objects are being canceled concurrently.

If it is public and its true (and this is not expected) i would track down all the code using it and try to work out who cancelled it and why, and if this fits in with your desired architecture

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
  • Thanks for the reply, I'm aware it shouldn't do this no matter the declaration type. I can't track anything since there is nothing to track, as I said, just by declaring it public that already cancel it which is terrible and plain dumb. I think my project might be corrupted, pasting the same class into another project works. So yeah, I solved it pretty quickly, but not before wasting hours verifying every single line of code. Gj Microsoft! – qckmini6 Oct 29 '18 at 00:07
  • @qckmini6 i like your enthusiasm and youthful exuberance – TheGeneral Oct 29 '18 at 00:19