Task.Run with cancellation support

Consider this example Task.Run . It shows how to create a task with cancellation support.

I am doing something like this:

 Task.Run(()=>{while (!token.IsCancellationRequested()) {...}}, token); 

My questions:

  • Since I already have a reference to the cancellation token, why is the goal of passing it as a parameter to the Task.Run call?

  • I often see the following code in examples:

    if (token.IsCancellationRequested) token.ThrowIfCancellationRequested();

What is the purpose of this code? Why not just return from a method?

+3
c # task-parallel-library
source share
1 answer
  • If you pass the cancellation token to Task.Run , if the token is canceled before the task starts, it will never start when you save resources (I mean that I do not create threads, etc.).

  • If you just return from a method, the task state will not be Canceled , it will be RanToCompletion . Clearly, this is not what you expect.

Alternatively, you can throw an OperationCanceledException with the CancellationToken as parameter, which will make Task.Status equal Canceled , but this is a complicated and detailed way. token.ThrowIfCancellationRequested is concise.

You can simply use token.ThrowIfCancellationRequested(); , no need to check token.IsCancellationRequested . ThrowIfCancellationRequested method already does this.

+7
source share

All Articles