gpt4 book ai didi

c# - 定期计时器在运行 61 次后意外停止

转载 作者:太空狗 更新时间:2023-10-29 21:22:46 24 4
gpt4 key购买 nike

以下直接的周期性计时器(应该无限运行)在运行 61 次后停止。如果我更改为 .FromMinutes(10) 也是如此:

static void Main(string[] args) {
var timerEvery5 = new Timer(
new TimerCallback((o) => Console.WriteLine("5-minutes handler launched at {0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm"))),
null,
new TimeSpan(0), // first run immediately
TimeSpan.FromMinutes(5)); // then every 5 minutes
for (; ; )
Thread.Sleep(23457);
}

我在几个带有 .Net 4.5 的 Windows 8 64 位系统上尝试过。该程序是从命令 shell 编译和运行的。是错误还是我遗漏了什么?

最佳答案

我相信由于运行时优化并确定方法中不再引用 timerEvery5 变量,您的计时器正在收集垃圾...尝试将其设置为静态变量并看看它是否解决了问题。或者在 sleep 循环之后调用 GC.KeepAlive(timerEvery5);,因为该调用在方法执行之前保持变量未被 GC(有点不直观)。

编辑:通过此链接:http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx请参阅第一个示例,因为它是一个类似的问题。引自示例:

// If the timer is declared in a long-running method, use 
// KeepAlive to prevent garbage collection from occurring
// before the method ends.
//GC.KeepAlive(aTimer);

关于c# - 定期计时器在运行 61 次后意外停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18750157/

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