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

标签 c# task

我有一个在我的应用程序后台定期运行的任务。当我第一次运行它时,一切正常,任务运行完美结束。但是第二次和之后每当我使用 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/

相关文章:

c# - OData 无法序列化空资源

c# - 等待抽象函数完成 c#

c# - Task.Delay().Wait() 是怎么回事?

synchronization - 如何让许多 FreeRTOS 任务等待彼此完成初始化

c# - 忽略生成查询表达式 EF Core 的 ThenIninclude 语句

c# - 在 C# 中将 DateTime 转换为 MM/dd/yyyy

c# - 在 ASP.NET Web 应用程序中将异步/等待与任务一起使用时,UI 线程被阻塞

c# - 如何在一个完成的线程满足条件后立即取消其他线程

javascript - C# UWP 中的发射格式

c# - String.Split 针对 FTP 文件