如何像中止线程一样中止任务(Thread.Abort 方法)? [英] How to abort a Task like aborting a Thread (Thread.Abort method)?

查看:38
本文介绍了如何像中止线程一样中止任务(Thread.Abort 方法)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以像这样中止Thread:

Thread thread = new Thread(SomeMethod);
.
.
.
thread.Abort();

但是我可以以相同的方式中止 Task(在 .Net 4.0 中)而不是通过取消机制.我想立即终止任务.

But can I abort a Task (in .Net 4.0) in the same way not by cancellation mechanism. I want to kill the Task immediately.

推荐答案

  1. 你不应该使用 Thread.Abort()
  2. 任务可以取消但不能中止.

Thread.Abort() 方法是(严重)已弃用.

The Thread.Abort() method is (severely) deprecated.

线程和任务在停止时都应该合作,否则你会冒着让系统处于不稳定/未定义状态的风险.

Both Threads and Tasks should cooperate when being stopped, otherwise you run the risk of leaving the system in a unstable/undefined state.

如果您确实需要运行一个进程并从外部杀死它,唯一安全的选择是在单独的 AppDomain 中运行它.

If you do need to run a Process and kill it from the outside, the only safe option is to run it in a separate AppDomain.

这个答案是关于 .net 3.5 及更早版本的.

This answer is about .net 3.5 and earlier.

从那时起,线程中止处理得到了改进,a.o.通过改变 finally 块的工作方式.

Thread-abort handling has been improved since then, a.o. by changing the way finally blocks work.

但是 Thread.Abort 仍然是您应该始终尽量避免的可疑解决方案.

But Thread.Abort is still a suspect solution that you should always try to avoid.

这篇关于如何像中止线程一样中止任务(Thread.Abort 方法)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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