c# - ThreadAbortException 是否仍然强制执行 finally (try/catch) 部分中的代码?

标签 c# timer try-catch-finally threadabortexception

我有一个 System.Timers.Timer 计时器,它的 AutoReset 设置为 false。我使用 try/finally 来确保我在 callback 结束时 Start 计时器(我以这种方式使用计时器来防止重叠回调执行)。代码:

// inside timer call back
try
{
    // Do something
}
finally
{
    timer.Start(); // Is this line always executed?
}

我的问题是如果正在执行的线程中止会发生什么? finally 部分是否仍在执行,或者没有线程运行该部分?

最佳答案

官方来源...

When a call is made to the Abort method to destroy a thread, the common language runtime throws a ThreadAbortException. 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. If you want to wait until the aborted thread has ended, you can call the Thread.Join method. Join is a blocking call that does not return until the thread actually stops executing.

MSDN 上阅读更多相关信息.

关于c# - ThreadAbortException 是否仍然强制执行 finally (try/catch) 部分中的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6099382/

相关文章:

c# - 以编程方式在 View 中创建列

javascript - 为什么这个微任务在事件循环中先于宏任务执行?

java - 在包含 return 的 try/catch block 之后执行语句

c# - 销售点申请收据打印

javascript - 无法看到警报 - mvc5 通过 TempData 进行引导

java - 安排 24 个不同计时器的最有效方法

C# 计时器与服务中的线程

c# - 如何在C#中使用try-finally构造?

.net - 返回最后一 block ……为什么不呢?

c# - 在模型中动态设置正则表达式