如何强制取消任务?
假设有一个任务大约包含以下操作:
Task someTask = new Task(() => {
while(!IsCancellationRequested) {
Do_something_over_a_long_period_of_time();
token.ThrowIfCancellationRequested();
Do_something_over_a_long_period_of_time();
token.ThrowIfCancellationRequested();
Do_something_over_a_long_period_of_time();
token.ThrowIfCancellationRequested();
}
});
someTask.Start();
并且有相当不耐烦的用户。他们渴望立即终止我的申请。他们不想在长时间的行动进行时等待。
我曾经使用 Thread 类,并且能够通过调用 Abort() 命令立即中止所有线程。
如何立即中止我的任务?
谢谢。
Assume, there is a task containing the following actions approximately:
Task someTask = new Task(() => {
while(!IsCancellationRequested) {
Do_something_over_a_long_period_of_time();
token.ThrowIfCancellationRequested();
Do_something_over_a_long_period_of_time();
token.ThrowIfCancellationRequested();
Do_something_over_a_long_period_of_time();
token.ThrowIfCancellationRequested();
}
});
someTask.Start();
And there are pretty impatient users. They long to terminate my application immediately. They don't want to wait while long action is running.
I used to use the Thread
class and was able to abort all my threads immediately with invoking the Abort()
command.
How do I abort my tasks immediately?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能以不合作的方式强制任务中止。以不受控制的方式中止线程是不安全的,因此故意不支持。
您应该将您的
Do_something_over_a_long_period_of_time
调用设置为可取消(即将令牌传递给它们,并让它们也定期检查)。编辑:正如另一个答案中所述,您可以通过确保所有前台线程都已终止来终止应用程序。但您需要注意,您的任务不一定有机会干净地终止。如果他们正在执行诸如写入文件之类的操作,您可能希望等到注意到取消为止,以避免损坏持久状态。
You can't force a task to abort in an uncooperative manner. Aborting a thread in an uncontrolled way is unsafe, and thus deliberately unsupported.
You should make your
Do_something_over_a_long_period_of_time
calls cancellable instead (i.e. pass them the token, and make them check regularly too).EDIT: As noted in another answer, you can kill the application just by making sure all the foreground threads have terminated. But you need to be aware that your tasks won't necessarily have had a chance to terminate cleanly. If they're doing things like writing files, you may well want to wait until the cancellation has been noticed, to avoid corrupting persisted state.
默认情况下,任务作为后台任务在线程池上运行。您可以安全地退出应用程序,而无需担心后台线程。
所以只要你想退出你的进程就没有问题。
请注意,Thread.Abort() 速度很快,但不安全。即使对于退出应用程序也不会,但它很少会导致真正的问题。
By default, Tasks run on the ThreadPool as background tasks. You can safely exit the application without bothering about background threads.
So as long as you want to quit your process there is no problem.
Note that Thread.Abort() was quick but not safe. Not even for a quitting application, but then it would seldom cause a real problem.