This MSDN example can be written without the use of CancellationTokenSource
, one can use CancellationToken directly.
Is it OK to use a CancellationToken
directly or is it something that should never be done? I have not seen any example of direct use on MSDN and that makes me wounder if it is OK to do so.
Update
Cod below expands on accepted answer with a small set of test cases that demonstrate that CancellationToken
is immutable and thus CancellationTokenSource
has to be used if control of token is desired.
It is worth mentioning that Token property on CancellationTokenSource
returns new object with each call.
[TestMethod]
public void CancellationTokenProps() {
CancellationToken token = new CancellationToken(canceled:false);
Assert.IsFalse(token.IsCancellationRequested);
Assert.IsFalse(token.CanBeCanceled);
}
[TestMethod]
public void CancellationTokenSourceProps() {
CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token1 = source.Token;
CancellationToken token2 = source.Token;
Assert.IsFalse(Object.ReferenceEquals(token1, token2));
Assert.IsTrue(token1.CanBeCanceled);
Assert.IsFalse(token1.IsCancellationRequested);
Assert.IsFalse(source.IsCancellationRequested);
source.Cancel(true);
Assert.IsTrue(source.IsCancellationRequested);
Assert.IsTrue(token1.IsCancellationRequested);
}
No. You can't cancel a CancellationToken
directly without invoking CancealltionTokenSource.Cancel
which means that using only the Token is pretty useless (it will never be signaled, you could just use CancellationToken.None
instead)
Cancellation works where one side has the means to notify cancellation (CancellationTokenSource
) and the other side needs to observe that and get cancelled (with a CancellationToken
)
*You could simply create a CancellationToken
directly while passing a bool
signifying if the token is already cancelled or not, but you can't change that throughout the application's lifetime, so the use cases are very rare.