可以在Final块的中间引发ThreadAbortException吗? [英] Can ThreadAbortException be raised in the middle of a Finally Block?
问题描述
假定以下代码在单独的线程中运行:
try{
var stuffToDispose = new SomeClassThatNeedsDisposing();
//doing thing with stuffToDispose
}
finally{
if(stuffToDispose != null)
stuffToDispose.Dispose();
}
,并使用引发ThreadAbortException
的机制中止该线程. ThreadAbortException
是否可以在null检查和Dispose()之间发生?阿卡,在最后一块的中间吗?
finally{
if(stuffToDispose != null)
//This is where the Exception would strike
stuffToDispose.Dispose();
}
我很确定答案是否定的,但是其他人似乎相信这是可能的.
在 .NET Framework 中,ThreadAbortException
在catch
和finally
块中均以特殊方式处理:>
- 如果捕获到
ThreadAbortException
,它将在catch
块的末尾自动重新引发(除非被Thread.ResetAbort
抑制) - 在
finally
块中,ThreadAbortException
直到整个块的结尾都不会被激活".这是预期的行为.因此,有时您会发现晦涩的代码带有try {}
块且为空的try {}
块,其中所有内容均在finally
部分中.它保证了本节不会被中止.
另一方面, .NET Core 不支持Thread.Abort
(引发PlatformNotSupportedException
). ThreadAbortException
本身尚未删除(出于兼容性原因),因此您仍然可以显式抛出它,但我认为仍然不能如上所述进行处理(我没有对其进行测试).
Asuming the following code is running in a seperate Thread:
try{
var stuffToDispose = new SomeClassThatNeedsDisposing();
//doing thing with stuffToDispose
}
finally{
if(stuffToDispose != null)
stuffToDispose.Dispose();
}
and this thread is aborted using the mechanic that raises the ThreadAbortException
. Could the ThreadAbortException
happen between the null-check and the Dispose()? Aka, in the middle of the finally block?
finally{
if(stuffToDispose != null)
//This is where the Exception would strike
stuffToDispose.Dispose();
}
I am pretty sure the answer is no, but someone else seems convinced it is possible.
In .NET Framework ThreadAbortException
is handled in a special way both in catch
and finally
blocks:
- If a
ThreadAbortException
is caught, it is automatically re-raised at the end of thecatch
block (unless it is suppressed byThread.ResetAbort
) - In a
finally
block theThreadAbortException
will not be 'activated' until the end of the whole block. This is an intended behavior. And that's why you can find sometimes obscure codes with and emptytry {}
block where everything is in thefinally
section. It guarantees that this section will not be aborted.
On the other hand, .NET Core does not support Thread.Abort
(throws a PlatformNotSupportedException
). The ThreadAbortException
itself has not been removed (for compatibility reasons) so you can still throw it explicitly but I don't think it is still handled as described above (I did not test it).
这篇关于可以在Final块的中间引发ThreadAbortException吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!