Reputation: 113
I often see the following code which is the first view looks good since one is used to check a precondition before doing something else.
But when one reads the name of the method it feels like the preceding if statement already is included in the method itself. So is there any reason to write the code like it is in this example or could one just skip the if-statement and run ThrowIfCancellationRequested
directly.
Of course its a different thing if one need to cleanup before exiting then I fully understand the use of the if-statement.
if (cancellationToken.IsCancellationRequested)
{
cancellationToken.ThrowIfCancellationRequested();
}
Upvotes: 7
Views: 1749
Reputation: 43399
Here is the source code of the ThrowIfCancellationRequested
method:
public void ThrowIfCancellationRequested()
{
if (IsCancellationRequested)
ThrowOperationCanceledException();
}
It should be pretty obvious that checking the IsCancellationRequested
property before calling this method serves no purpose, other than converting a tiny amount of electricity to heat.
Upvotes: 3
Reputation: 287
In short: there is no reason to check both.
cancellationToken.ThrowIfCancellationRequested()
and cancellationToken.IsCancellationRequested
are different approaches to achieve the same goal.
Checking cancellationToken.IsCancellationRequested
is a so-called "soft" way of cancelling a task.
Setting cancellationToken.ThrowIfCancellationRequested()
is often considered to be the recommended option.
You can find more information on proper task cancellation here and here.
Upvotes: 5