Can ThreadAbortException skip finally?

后端 未结 3 942
花落未央
花落未央 2020-12-11 06:43

Everything I\'ve read claims an abort on a thread will execute the finally block before ending from a ThreadAbortException. I wanted to confirm this so I can plan on how to

3条回答
  •  离开以前
    2020-12-11 07:27

    Docs say: ThreadAbortException is a special exception that can be caught, but it will automatically be raised again at the end of the catch block. When this exception is raised, the runtime executes all the finally blocks before ending the thread. Because the thread can do an unbounded computation in the finally blocks or call Thread.ResetAbort to cancel the abort, there is no guarantee that the thread will ever end.

    I'm pretty sure your thread is being dumped because you exit the method and lose a reference to it, and so it gets collected by the Garbage Collector. Try making the testThread variable a field member of the class and see what happens.

    That, or you have a race condition since the threads run in parallel: the main thread is finishing before the spun-up test thread can output the finally data (Exceptions are expensive and take time to reach catch or finally blocks).

提交回复
热议问题