gpt4 book ai didi

c# - 重新启动已完成的任务

转载 作者:太空狗 更新时间:2023-10-29 20:02:50 24 4
gpt4 key购买 nike

我有一个在我的应用程序后台定期运行的任务。当我第一次运行它时,一切正常,任务运行完美结束。但是第二次和之后每当我使用 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 (实际上我可以推荐阅读更多他关于任务的文章)

  1. 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com