How can I detect a ThreadAbortException in a finally block? (.NET)

前端 未结 7 2171
太阳男子
太阳男子 2020-12-15 12:08

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

相关标签:
7条回答
  • 2020-12-15 12:15

    I don't think that it's possible.

    Why do you need to handle the ThreadAbortException in the first place? Calling thread.Abort() is usually a sign of bad design. Have a flag variable that when set to true will simply return; from the thread function, after appropriate cleanup of course.

    That way you won't need to worry about the exception.

    0 讨论(0)
  • 2020-12-15 12:16

    I agree with arul. Calling Thread.Abort() is a sign of bad design.

    Let me quote Peter Ritchie from MSDN: Thread.Abort (emphasis is mine):

    There's many reasons not to use Thread.Abort and ThreadAbortException

    On certain platforms (like x64 and IA64) the abort can occur before Monitor.Enter and a try block (even with lock/SyncLock), leaving the monitor orphaned. The ThreadAbortException can occur in 3rd party code not written to handle thread abort. The thread can be aborted while processing a finally block in .NET 1.x Uses exceptions for normal control flow logic. Asynchronous exception can interrupt modification of shard state or resources, leaving them corrupted.

    For more detail see:
    http://msmvps.com/blogs/peterritchie/archive/2007/08/22/thead-abort-is-a-sign-of-a-poorly-designed-program.aspx
    http://www.bluebytesoftware.com/blog/2007/01/30/MonitorEnterThreadAbortsAndOrphanedLocks.aspx
    http://blogs.msdn.com/ericlippert/archive/2007/08/17/subtleties-of-c-il-codegen.aspx

    0 讨论(0)
  • 2020-12-15 12:23

    You can actually execute code in the catch statement just fine for a ThreadAbortException. The problem is that the exception will be rethrown once execution leaves the catch block.

    If you want to actually stop the exception from continuing you can call Thread.ResetAbort(). This does require full trust though and unless you have a specific scenario, it's almost certainly the wrong thing to do.

    ThreadAbortException

    0 讨论(0)
  • 2020-12-15 12:27

    Read about Constrained Execution Regions.

    Specifically, the RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup method will be useful here.

    0 讨论(0)
  • 2020-12-15 12:28

    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() { }
    
    0 讨论(0)
  • 2020-12-15 12:31

    If calling Thread.Abort is bad design why does SQL Server call it on a thread that is running user code? Because this is exactly how a query cancel is handled and it causes nightmares.

    0 讨论(0)
提交回复
热议问题