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

本文关键字:意外 计时器 运行 | 更新日期: 2023-09-27 18:31:02

以下直接的周期性计时器(应该无限运行)在运行 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 8 4.5的Windows 8 64位系统上尝试过。该程序从命令外壳编译和运行。是错误还是我错过了什么?

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

我相信

由于运行时优化并确定方法中不再引用timerEvery5变量,您的计时器正在被垃圾回收......尝试将其设置为静态变量,看看是否可以解决问题。那个或调用GC.KeepAlive(timerEvery5);睡眠循环之后,因为该调用使变量保持非GC'd,直到方法被执行(有点不直观)。

编辑:根据此链接: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);