Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task.Run with cancellation support

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:

  1. Since I already have a reference to the cancellation token, why the purpose of passing it as a parameter to the Task.Run invocation?

  2. 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?

like image 806
daramasala Avatar asked Mar 18 '23 00:03

daramasala


1 Answers

  1. 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).

  2. 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.

like image 135
Sriram Sakthivel Avatar answered Mar 28 '23 13:03

Sriram Sakthivel