重新启动已完成的任务 [英] Restart a completed task

查看:150
本文介绍了重新启动已完成的任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在我的应用程序后台定期运行的任务.当我第一次运行它时,一切正常,任务运行完美结束.但是第二次之后,每当我使用 task.Start() 时,它都会抛出异常:

<块引用>

在 mscorlib.dll 中发生类型为System.InvalidOperationException"的未处理异常附加信息:不能对已完成的任务调用 Start.

我确定我的任务函数运行到最后..我应该怎么做才能定期运行任务?

解决方案

StephenTaub 对此进行了解释(我实际上可以推荐阅读他关于 Tasks 的更多文章)

<块引用>

  1. 问题:我可以在同一个任务上多次调用 Start 吗?

没有.任务只能从 Created 状态转换一次,而 Start 将任务从 Created 状态转换:因此,Start 只能使用一次.任何对不在 Created 状态的任务调用 Start 的尝试都将导致异常.Start 方法使用同步来确保 Task 对象保持一致状态,即使 Start 被多次并发调用......只有一次调用可能会成功.

...这也是你所看到的.例如,您可以使用计时器并每次启动一个新任务.
如果您需要检查一次只运行一个,您可以检查当前正在运行的任务上的 TaskStatus.RanToCompletion

I have a Task that run periodically in the background of my application. When I run it for the first time everything is ok and the Task run to end perfectly. But for the second time and after that whenever I use task.Start() it throws an exception:

An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll Additional information: Start may not be called on a task that has completed.

I am sure that my task function ran to the end.. what should I do to run the task periodically?

解决方案

Stephen Taub explains it (I can actually recommend reading more of his articles regarding Tasks)

  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.

.. Which is what you see as well. You can use for instance a timer and start a new Task each time.
If you need to check that only one run at a time, you can check for TaskStatus.RanToCompletion on the task that is currently running

这篇关于重新启动已完成的任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆