Reputation: 40092
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
});
}
}
Upvotes: 40
Views: 44881
Reputation: 4283
Following @Mohammad Kohanrooz answer, here is my extension method:
/// <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;
}
Use it like:
if(myOwnTask.IsRunning())
{
Logger.Log("Task is already running");
}
else
{
Logger.Log("Starting new task");
myOwnTask = StartNewTask();
}
Upvotes: 0
Reputation: 19
Even easier:
if (task?.IsCompleted ?? true)
task = TaskFunction();
Upvotes: 1
Reputation: 10622
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
});
}
}
Upvotes: 15
Reputation: 21
You can check it with:
if ((taskX == null) || (taskX.IsCompleted))
{
// start Task
taskX.Start();
//or
taskX = task.Factory.StartNew(() =>
{
//??
}
}
Upvotes: 2
Reputation: 40092
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
, orCanceled
.
But it appears to return true in the TaskStatus.WaitingForActivation
state too.
Upvotes: 38