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 be RanToCompletion
. Clearly this isn't what you'll expect.
Alternatively you could throw OperationCanceledException
with the CancellationToken
as parameter, that will make the Task.Status
to be Canceled
, but this is the hard and verbose way. token.ThrowIfCancellationRequested
is concise.
You could simply use token.ThrowIfCancellationRequested();
, no need to check for token.IsCancellationRequested
. ThrowIfCancellationRequested
method already does this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With