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);
}