Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing cancellation token to calling method VS task constructor?

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?

like image 229
Mark S Avatar asked Jun 18 '16 11:06

Mark S


1 Answers

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.

like image 172
i3arnon Avatar answered Oct 09 '22 03:10

i3arnon