如何中止任务,例如中止线程(Thread.Abort方法)? [英] How to abort a Task like aborting a Thread (Thread.Abort method)?
问题描述
我们可以像这样终止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.
推荐答案
- 您不应使用Thread.Abort()
- 可以取消任务,但不能中止.
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.
如果您确实需要运行一个Process并从外部将其杀死,那么唯一安全的选择是在单独的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.
此后,线程中止处理得到了改进.通过更改最终阻止工作的方式.
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屋!