gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:11:14 26 4
gpt4 key购买 nike

我有一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com