使用 Thread.Abort() 有什么问题 [英] What's wrong with using Thread.Abort()

查看:38
本文介绍了使用 Thread.Abort() 有什么问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道你不应该使用

So I know that you shouldn't use

Thread.Abort()

但我从来没有得到很好的解释.是否有性能损失或一些隐藏的问题?

But I've never been given a good explanation. Is there a performance penalty or some hidden gotcha?

我知道你不能忽略/吞下 ThreadAbortException(这是有道理的)

I know you can't ignore/swallow the ThreadAbortException (which makes sense)

推荐答案

除了这里的所有其他好的答案之外,让我补充一点,无法保证对 Thread.Abort 的调用实际上会中止线程问题,曾经.可以(虽然不是特别容易)强化"线程以防止被中止.例如,如果您因为认为某个线程正在运行恶意代码而中止一个线程,那么该恶意代码可能会抵抗自己的破坏.

In addition to all of the other good answers here, let me add that there is no guarantee whatsoever that a call to Thread.Abort will actually abort the thread in question, ever. It is possible (though not particularly easy) to "harden" a thread against being aborted. If, for example, you are aborting a thread because you believe it to be running hostile code then the hostile code could be resisting its own destruction.

如果您有一个长时间运行的操作,涉及您不拥有的代码并且必须彻底删除,那么正确的方法是将该代码放入其自己的进程,而不是它的自己的线程.(并且最好在该进程中高度安全限制的应用程序域中.)然后您可以干净地终止该进程.

If you have a long-running operation involving code that you do not own that must be taken down cleanly, the correct way to do this is to put that code in its own process, not its own thread. (And preferably in a highly security-restricted appdomain in that process.) You can then cleanly kill the process.

简而言之,Thread.Abort 充其量表明设计不佳,可能不可靠,并且极其危险.应该不惜一切代价避免它;您应该考虑中止线程的唯一时间是在某种紧急关闭"代码中,您试图尽可能干净地拆除应用程序域.

In short, Thread.Abort is at best indicative of bad design, possibly unreliable, and extremely dangerous. It should be avoided at all costs; the only time you should ever even consider aborting a thread is in some sort of "emergency shutdown" code where you are attempting to tear down an appdomain as cleanly as possible.

这篇关于使用 Thread.Abort() 有什么问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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