如何强制取消任务? [英] How do I force a task cancellation?

查看:72
本文介绍了如何强制取消任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设,有一个任务大约包含以下操作:

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.

我曾经使用Thread类,并且能够通过调用Abort()命令立即中止所有线程.

I used to use the Thread class and was able to abort all my threads immediately with invoking the Abort() command.

如何立即中止任务?

谢谢.

推荐答案

他们渴望立即终止我的申请.他们不想等待长时间的操作.

They long to terminate my application immediately. They dont want to wait while long action is running.

默认情况下,任务在ThreadPool上作为后台任务运行.您可以安全地退出应用程序,而不必担心后台线程.

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.

请注意,Thread.Abort()快速但不安全.即使对于退出的应用程序也不是,但是那样的话很少会引起真正的问题.

Note that Thread.Abort() was quick but not safe. Not even for a quitting application, but then it would seldom cause a real problem.

这篇关于如何强制取消任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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