Check if task is already running before starting new

前端 未结 4 1606
旧时难觅i
旧时难觅i 2020-12-29 02:32

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

4条回答
  •  梦谈多话
    2020-12-29 03:10

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

提交回复
热议问题