简体   繁体   中英

Why should I check IsCancellationRequested before calling ThrowIfCancellationRequested()

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();
}

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM