One way to pass a cancellation token is:
/* Cancellation token passed as method parameter */
Task task = Task.Run( () => { LongTask(1000000, cancellationToken.Token); });
Another way is:
/* Cancellation Token passed as task constructor */
Task task = Task.Run( () => { LongTask(1000000); }, cancellationToken.Token);
What is the difference?
The first passes a token to your method, where you can do what you want with it. The second passes the token to Task.Run
that associates the task with that token.
Since cancellation in .NET is cooperative Task.Run
can only cancel your task if it hadn't started executing yet (which isn't that useful) and your method can only check the token from time to time and throw if cancellation was requested but that will mark the task as faulted instead of cancelled.
For a complete solution you should actually do both:
var task = Task.Run(() => LongTask(1000000, cancellationToken), cancellationToken);
That way the task is associated with the token and you can check the token for cancellation.
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