C# 在开始新任务之前检查任务是否已经在运行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19197376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if task is already running before starting new
提问by Dave 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
});
}
}
采纳答案by Dave New
As suggested by Jon Skeet, the Task.IsCompleted
is the better option.
正如 Jon Skeet 所建议的,这Task.IsCompleted
是更好的选择。
According to MSDN:
根据MSDN:
IsCompleted
will return true when the task is in one of the three final states:RanToCompletion
,Faulted
, orCanceled
.
IsCompleted
当任务是在三个最终状态之一将返回true:RanToCompletion
,Faulted
或Canceled
。
But it appears to return true in the TaskStatus.WaitingForActivation
state too.
但它似乎也返回 trueTaskStatus.WaitingForActivation
状态。
回答by Sayka
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
});
}
}
回答by guest123
You can check it with:
您可以通过以下方式检查:
if ((taskX == null) || (taskX.IsCompleted))
{
// start Task
taskX.Start();
//or
taskX = task.Factory.StartNew(() =>
{
//??
}
}
回答by Mohammad Kohanrooz
Even easier:
更简单:
if (task?.IsCompleted ?? true)
task = TaskFunction();