ThreadAbortException [英] ThreadAbortException

查看:181
本文介绍了ThreadAbortException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我们有像在单独的线程这一运行一些代码:

Let's say we have some code like this running in the separate thread:

private static void ThreadFunc() {
    ulong counter = 0;

    while (true) {

        try {
            Console.WriteLine( "{0}", counter++ );
        }
        catch (ThreadAbortException) {
            Console.WriteLine( "Abort!" );
        }

    }
}

Thread.Abort的()之称,是有可能的异常catch块之外抛出?

When Thread.Abort() is called, is it possible that the exception is thrown outside of catch block?

推荐答案

其实是的, ThreadAbortException 是特殊的。即使你处理它,它会自动由CLR在try / catch语句的结束重新抛出/最后。 (正如在评论中指出,它可以与 抑制ResetAbort 但该点的代码气味像臭鱼。)

Actually yes, a ThreadAbortException is special. Even if you handle it, it will be automatically re-thrown by the CLR at the end of the try/catch/finally. (As noted in the comments, it can be suppressed with ResetAbort but by that point the code smells like rotten fish.)

不要甚至提及,虽然没有明显的可执行代码你的try / catch外/最后,循环的每次迭代的余地很小持续时间,从而中止可以在你的try块外面发生的外面缠。

Not to mention even though there is no obvious executable code outside of your try/catch/finally, every iteration of the loop winds up outside of the scope for a small duration so the abort could occur outside of your try block.

除非你实际上是做在catch块的东西,我只想做一个try /终于和不用担心 ThreadAbortException 。有没有使用终止线程的更好的方式 Thread.Abort的这在一个不可预知的点不仅混乱中断你的代码,它也不能保证,因为工作,如果你的线程是目前呼唤一些非托管代码,线程不会中止,直到控制返回到托管代码。

Unless you are actually doing something in the catch block, I would just make a try/finally and don't worry about ThreadAbortException. There are much better ways of aborting a thread without using Thread.Abort which not only chaotically interrupts your code at an unpredictable point, it's also not guaranteed to work because if your thread is currently calling out to some unmanaged code, the thread will not abort until control returns to managed code.

这是最好使用某种类型的同步原语,如<一个HREF =htt​​p://msdn.microsoft.com/en-us/library/system.threading.manualresetevent.aspx> 的ManualResetEvent 充当旗告诉你的线程时退出。你甚至可以使用布尔型字段用于此目的是BackgroundWorker的做什么。

It's much better to use some type of synchronization primitive such as a ManualResetEvent to act as a flag telling your thread when to exit. You could even use a boolean field for this purpose which is what the BackgroundWorker does.

这篇关于ThreadAbortException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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