Passing cancellation token to calling method VS task constructor? Passing cancellation token to calling method VS task constructor? multithreading multithreading

Passing cancellation token to calling method VS task constructor?


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.