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

本文关键字:任务 是否 运行 检查 开始 新任务 | 更新日期: 2023-09-27 18:34:12

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

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

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

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

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

根据MSDN:

当任务位于三个任务之一中时,IsCompleted将返回 true。 最终状态:RanToCompletionFaultedCanceled

但在TaskStatus.WaitingForActivation州,它似乎也回归了。

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

你可以用以下方法检查它:

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

更简单:

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

按照 Kohanrooz @Mohammad答案,这是我的扩展方法:

/// <summary>
/// Checks if task is running.
/// </summary>
/// <param name="task">Task to evaluate</param>
/// <returns>True if task is not completed or it's value is null</returns>
public static bool IsRunning(this Task task)
{
    return !task?.IsCompleted ?? false;
}

像这样使用它:

if(myOwnTask.IsRunning())
{
    Logger.Log("Task is already running");  
}
else
{
    Logger.Log("Starting new task");    
    myOwnTask = StartNewTask(); 
}