Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is a curious problem.</p> <p>The code you posted <em>should</em> work. It seems there's some kind of optimization going on that decides not to call your catch handler.</p> <p>So, I wanted to detect the exception with this:</p> <pre><code>bool threadAborted = true; try { try { } finally { /* critical code */ } threadAborted = false; } finally { Console.WriteLine("Thread aborted? {0}", threadAborted); } Console.WriteLine("Done"); </code></pre> <p>(My actual code just slept in that critical code section, so I could be sure it would abort after that finally.)</p> <p>It printed:</p> <blockquote> <p>Thread aborted? False</p> </blockquote> <p>Hmmm, strange indeed!</p> <p>So I thought about doing a little bit more work there, to trick any "smart" optimizations:</p> <pre><code>bool threadAborted = true; try { try { } finally { /* critical code */ } threadAborted = AmIEvil(); } finally { Console.WriteLine("Thread aborted? {0}", threadAborted); } Console.WriteLine("Done"); </code></pre> <p>Where <code>AmIEvil</code> is just:</p> <pre><code>[MethodImpl(MethodImplOptions.NoInlining)] static bool AmIEvil() { return false; } </code></pre> <p>Finally it printed:</p> <blockquote> <p>Thread aborted? True</p> </blockquote> <p>And there you have it. Use this in your code:</p> <pre><code>try { try { } finally { /* critical code */ } NoOp(); } catch (Exception ex) { // ThreadAbortException is caught here now! } </code></pre> <p>Where <code>NoOp</code> is just:</p> <pre><code>[MethodImpl(MethodImplOptions.NoInlining)] static void NoOp() { } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload