Consider this Task.Run
example. It shows how to create a task with cancellation support.
I am doing something similar:
Task.Run(()=>{while (!token.IsCancellationRequested()) {...}}, token);
My questions:
Since I already have a reference to the cancellation token, why the purpose of passing it as a parameter to the
Task.Run
invocation?I often see the following code in examples:
if (token.IsCancellationRequested) token.ThrowIfCancellationRequested();
What's the purpose of this code? Why not just return
from the method?
If you pass the cancellation token to
Task.Run
, if the token is cancelled before the Task is started, it will never be started saving you resources(I mean by not creating threads etc).If you just return from the method, the Task's Status will not be
Canceled
, it will beRanToCompletion
. Clearly this isn't what you'll expect.Alternatively you could throw
OperationCanceledException
with theCancellationToken
as parameter, that will make theTask.Status
to beCanceled
, but this is the hard and verbose way.token.ThrowIfCancellationRequested
is concise.You could simply use
token.ThrowIfCancellationRequested();
, no need to check fortoken.IsCancellationRequested
.ThrowIfCancellationRequested
method already does this.