1

If i create a CancellationToken instance is there any way to somehow change the IsCancellationRequested property or do I always need a CancellationTokenSource instance and its Cancel method for that? In other words, for correct cancellation of tasks, does it make sense to use new CancellationToken () or should we always use CancellationTokenSource.Token?

And if I always need to use CancellationTokenSource.Token, then in what situations might I need to instantiate CancellationToken separately? Why would I need to do new CancellationToken()? When can I just do CancellationToken = CancellationTokenSource.Token.

  • Take a look at this: https://stackoverflow.com/questions/14215784/why-cancellationtoken-is-separate-from-cancellationtokensource A lot of answers about the difference of these two, including one from someone who was involved in the design of these classes. – Codehack Nov 24 '21 at 03:14
  • Does this answer your question? [Why CancellationToken is separate from CancellationTokenSource?](https://stackoverflow.com/questions/14215784/why-cancellationtoken-is-separate-from-cancellationtokensource) – Codehack Nov 24 '21 at 03:17
  • No, why the token can exist separately from the CancellationTokenSource is not said there. There are general phrases. But there is no specifics. Give an example where a token is useful apart from the CancellationTokenSource. And yes, a token is not a class but a structure. Why would I need to do new CancellationToken()? When can I just do CancellationToken = CancellationTokenSource.Token. –  Nov 24 '21 at 03:32

1 Answers1

1

new CancellationToken() - or equivalently CancellationToken.None produces a cancellation token which never will be cancelled.

It is useful when you call a method expecting a CancellationToken, but your code does never intend to cancel the task.

Klaus Gütter
  • 11,151
  • 6
  • 31
  • 36
  • Thank you! In other words, the value of the IsCancellationRequested property cannot be changed in new CancellationToken (). And new CancellationToken () can be used where a CancellationToken needs to be passed, but it is not assumed that we are planning to cancel our operation at all. Did I understand correctly? –  Nov 24 '21 at 04:33
  • Indeed, IsCancellationRequested is a get-only property. If you want, you can have a look at the [source code](https://github.com/microsoft/referencesource/blob/master/mscorlib/system/threading/CancellationToken.cs) – Klaus Gütter Nov 24 '21 at 05:07