Search code examples
c#.netcancellationtokensourcecancellation-token

new CancellationToken() and IsCancellationRequested without CancellationTokenSource


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.


Solution

  • 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.