有一个在任务中执行的过程。我不希望其中一个同时执行。
这是检查任务是否已在运行的正确方法吗?
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
});
}
}
答案 0 :(得分:34)
根据Jon Skeet的建议,Task.IsCompleted
是更好的选择。
根据MSDN:
当任务处于三者之一时,
IsCompleted
将返回true 最终状态:RanToCompletion
,Faulted
或Canceled
。
但它似乎也在TaskStatus.WaitingForActivation
状态下返回true。
答案 1 :(得分:11)
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
});
}
}
答案 2 :(得分:2)
您可以查看:
if ((taskX == null) || (taskX.IsCompleted))
{
// start Task
taskX.Start();
//or
taskX = task.Factory.StartNew(() =>
{
//??
}
}