gpt4 book ai didi

c# - 停止时同步 Timers.Timer elapsed 方法

转载 作者:太空狗 更新时间:2023-10-29 21:06:55 26 4
gpt4 key购买 nike

引用来自 MSDN 的引述关于 System.Timers.Timer:

The Timer.Elapsed event is raised on a ThreadPool thread, so the event-handling method might run on one thread at the same time that a call to the Timer.Stop method runs on another thread. This might result in the Elapsed event being raised after the Stop method is called. This race condition cannot be prevented simply by comparing the SignalTime property with the time when the Stop method is called, because the event-handling method might already be executing when the Stop method is called, or might begin executing between the moment when the Stop method is called and the moment when the stop time is saved. If it is critical to prevent the thread that calls the Stop method from proceeding while the event-handling method is still executing, use a more robust synchronization mechanism such as the Monitor class or the CompareExchange method. Code that uses the CompareExchange method can be found in the example for the Timer.Stop method.

谁能举一个“健壮的同步机制,例如 Monitor 类”的例子来解释这到底是什么意思?

我认为这意味着以某种方式使用锁,但我不确定您将如何实现它。

最佳答案

可靠地停止 System.Timers.Timer 确实是一项重大工作。最严重的问题是,由于线程池调度程序算法,它用于调用 Elapsed 事件的线程池线程可能会备份。有几个备用电话并不罕见,拥有数百个在技术上是可能的。

您将需要两次同步,一次确保您仅在没有 Elapsed 事件处理程序运行时才停止计时器,另一次确保这些备份的 TP 线程不会造成任何伤害。像这样:

    System.Timers.Timer timer = new System.Timers.Timer();
object locker = new object();
ManualResetEvent timerDead = new ManualResetEvent(false);

private void Timer_Elapsed(object sender, ElapsedEventArgs e) {
lock (locker) {
if (timerDead.WaitOne(0)) return;
// etc...
}
}

private void StopTimer() {
lock (locker) {
timerDead.Set();
timer.Stop();
}
}

考虑将 AutoReset 属性设置为 false。这是另一种方式,Elapsed 事件是从捕获异常的内部 .NET 方法调用的。非常讨厌,您的计时器代码在没有任何诊断的情况下停止运行。我不知道历史,但肯定有另一个 MSFT 的团队对这个烂摊子气呼呼地写了 System.Threading.Timer。强烈推荐。

关于c# - 停止时同步 Timers.Timer elapsed 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4810498/

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