daramasala
daramasala

Reputation: 3030

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?

Upvotes: 4

Views: 2270

Answers (1)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73502

  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.

Upvotes: 7

Related Questions