我有一个在我的应用程序后台定期运行的任务。当我第一次运行它时,一切正常,任务运行完美结束。但是第二次和之后每当我使用 task.Start()
它都会抛出一个异常:
An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll Additional information: Start may not be called on a task that has completed.
我确信我的任务函数运行到了最后。我应该怎么做才能定期运行任务?
最佳答案
Stephen Taub explains it (实际上我可以推荐阅读更多他关于任务的文章)
- Question: Can I call Start more than once on the same Task?
No. A Task may only transition out of the Created state once, and Start transitions a Task out of the Created state: therefore, Start may only be used once. Any attempts to call Start on a Task not in the Created state will result in an exception. The Start method employs synchronization to ensure that the Task object remains in a consistent state even if Start is called multiple times concurrently… only one of those calls may succeed.
.. 这也是您所看到的。例如,您可以使用计时器并每次启动一个新任务。
如果您需要检查一次只运行一个,您可以检查当前正在运行的任务的 TaskStatus.RanToCompletion
关于c# - 重新启动已完成的任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24791493/