我如何检测在一个ThreadAbortException finally块? (。净) [英] How can I detect a ThreadAbortException in a finally block? (.NET)
问题描述
我有一个finally块(带一个空try块)一些关键的逻辑,因为我要保证code被执行,即使线程被中止。不过,我也想检测ThreadAbortException。我发现我的包裹关键的try /终于在一个try / catch块不捕获的ThreadAbortException。有什么方法来检测呢?
尝试 { 尝试 { } 最后 { //关键逻辑 } }赶上(例外前){ // ThreadAbortException没有抓到这里来,但抛出的异常 从关键逻辑中//是 }
这是一个奇怪的问题。
在code您发布的应该的工作。它似乎有某种优化的事情是决定不打电话给你的catch处理。
所以,我想检测例外,这样的:
布尔threadAborted = TRUE;
尝试 {
尝试 { }
最后{/ *临界code * /}
threadAborted = FALSE;
}
最后 {
Console.WriteLine(线程中止{0}?,threadAborted);
}
Console.WriteLine(完成);
(我的实际code只是睡在关键code部分,所以我可以肯定后,这将最终终止。)
据印:
主题中止?假
嗯,奇怪哉!
所以我想过做一点点工作,在那里,欺骗任何聪明优化:
布尔threadAborted = TRUE;
尝试 {
尝试 { }
最后{/ *临界code * /}
threadAborted = AmIEvil();
}
最后 {
Console.WriteLine(线程中止{0}?,threadAborted);
}
Console.WriteLine(完成);
其中, AmIEvil
就是:
[MethodImpl(MethodImplOptions.NoInlining)
静态布尔AmIEvil(){
返回false;
}
最后,它打印:
主题中止?真
和你有它。在code。使用这样的:
尝试{
尝试 { }
最后{/ *临界code * /}
空操作();
}
赶上(例外前){
// ThreadAbortException被抓到这里来了!
}
其中, NOOP
就是:
[MethodImpl(MethodImplOptions.NoInlining)
静态无效空操作(){}
I have some critical logic in a finally block (with an empty try block), because I want to guarantee that the code gets executed even if the thread is aborted. However, I'd also like to detect the ThreadAbortException. I've found that wrapping my critical try/finally block in a try/catch does not catch the ThreadAbortException. Is there any way to detect it?
try { try { } finally { // critical logic } } catch(Exception ex) { // ThreadAbortException is not caught here, but exceptions thrown // from within the critical logic are }
This is a curious problem.
The code you posted should work. It seems there's some kind of optimization going on that decides not to call your catch handler.
So, I wanted to detect the exception with this:
bool threadAborted = true;
try {
try { }
finally { /* critical code */ }
threadAborted = false;
}
finally {
Console.WriteLine("Thread aborted? {0}", threadAborted);
}
Console.WriteLine("Done");
(My actual code just slept in that critical code section, so I could be sure it would abort after that finally.)
It printed:
Thread aborted? False
Hmmm, strange indeed!
So I thought about doing a little bit more work there, to trick any "smart" optimizations:
bool threadAborted = true;
try {
try { }
finally { /* critical code */ }
threadAborted = AmIEvil();
}
finally {
Console.WriteLine("Thread aborted? {0}", threadAborted);
}
Console.WriteLine("Done");
Where AmIEvil
is just:
[MethodImpl(MethodImplOptions.NoInlining)]
static bool AmIEvil() {
return false;
}
Finally it printed:
Thread aborted? True
And there you have it. Use this in your code:
try {
try { }
finally { /* critical code */ }
NoOp();
}
catch (Exception ex) {
// ThreadAbortException is caught here now!
}
Where NoOp
is just:
[MethodImpl(MethodImplOptions.NoInlining)]
static void NoOp() { }
这篇关于我如何检测在一个ThreadAbortException finally块? (。净)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!