Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if task is already running before starting 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                
        });
    }
}
like image 600
Dave New Avatar asked Oct 05 '13 11:10

Dave New


3 Answers

As suggested by Jon Skeet, the Task.IsCompleted is the better option.

According to MSDN:

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

But it appears to return true in the TaskStatus.WaitingForActivation state too.

like image 84
Dave New Avatar answered Nov 05 '22 11:11

Dave New


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               
        });
    }
}
like image 37
Abdul Saleem Avatar answered Nov 05 '22 10:11

Abdul Saleem


You can check it with:

if ((taskX == null) || (taskX.IsCompleted))
{
   // start Task
   taskX.Start();
   //or
   taskX = task.Factory.StartNew(() =>
   {
      //??
   }
}
like image 2
guest123 Avatar answered Nov 05 '22 10:11

guest123