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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19197376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:22:12  来源:igfitidea点击:

Check if task is already running before starting new

c#.netparallel-processingtask-parallel-library

提问by Dave New

There is a process which is executed in a task. I do not want more than one of these to execute simultaneously.

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

Is this the correct way to check to see if a task is already running?

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

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

采纳答案by Dave New

As suggested by Jon Skeet, the Task.IsCompletedis the better option.

正如 Jon Skeet 所建议的,这Task.IsCompleted是更好的选择。

According to MSDN:

根据MSDN

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

IsCompleted当任务是在三个最终状态之一将返回true: RanToCompletionFaultedCanceled

But it appears to return true in the TaskStatus.WaitingForActivationstate too.

但它似乎也返回 trueTaskStatus.WaitingForActivation状态。

回答by Sayka

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

回答by guest123

You can check it with:

您可以通过以下方式检查:

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

回答by Mohammad Kohanrooz

Even easier:

更简单:

if (task?.IsCompleted ?? true)
    task = TaskFunction();