'Looking for Task.IsPending

I often do something like this:

if (task != null && !task.IsCompleted && !task.IsCanceled && !task.IsFaulted)
{
    // do something, e.g. cancel the task
}

It would be great to have task.IsPending as a shortcut for !task.IsCompleted && !task.IsCanceled && !task.IsFaulted, but it's not there. And task.Status == TaskStatus.Running is not the same, as task can be in one of the waiting states.

I have a custom Task extension method for this, but I'm curious why it is not there in the first place. Is checking for pending status this way considered somehow deprecated?



Solution 1:[1]

I think you're just looking for:

if (task != null && !task.IsCompleted)

As documented, IsCompleted covers faulted and canceled states as well as RanToCompletion:

IsCompleted will return true when the task is in one of the three final states: RanToCompletion, Faulted, or Canceled.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jon Skeet