在开始新任务之前检查任务是否已在运行

时间:2013-10-05 11:39:01

标签: c# .net parallel-processing task-parallel-library

有一个在任务中执行的过程。我不希望其中一个同时执行。

这是检查任务是否已在运行的正确方法吗?

private Task task;

public void StartTask()
{
    if (task != null && (task.Status == TaskStatus.Running || task.Status == TaskStatus.WaitingToRun || task.Status == TaskStatus.WaitingForActivation))
    {
        Logger.Log("Task has attempted to start while already running");
    }
    else
    {
        Logger.Log("Task has began");

        task = Task.Factory.StartNew(() =>
        {
            // Stuff                
        });
    }
}

3 个答案:

答案 0 :(得分:34)

根据Jon Skeet的建议,Task.IsCompleted是更好的选择。

根据MSDN

  当任务处于三者之一时,

IsCompleted将返回true   最终状态:RanToCompletionFaultedCanceled

但它似乎也在TaskStatus.WaitingForActivation状态下返回true。

答案 1 :(得分:11)

private Task task;

public void StartTask()
{
    if ((task != null) && (task.IsCompleted == false ||
                           task.Status == TaskStatus.Running ||
                           task.Status == TaskStatus.WaitingToRun ||
                           task.Status == TaskStatus.WaitingForActivation))
    {
        Logger.Log("Task is already running");
    }
    else
    {
        task = Task.Factory.StartNew(() =>
        {
            Logger.Log("Task has been started");
            // Do other things here               
        });
    }
}

答案 2 :(得分:2)

您可以查看:

if ((taskX == null) || (taskX.IsCompleted))
{
   // start Task
   taskX.Start();
   //or
   taskX = task.Factory.StartNew(() =>
   {
      //??
   }
}