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

时间:2013-09-11 19:59:39

标签: c#

以下直接定期计时器(应无限运行)在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编译和运行的。这是一个错误还是我错过了什么?

1 个答案:

答案 0 :(得分:8)

我相信你的计时器会因为运行时优化而收集垃圾,并确定方法中不再引用timerEvery5变量...尝试将其设置为静态变量并查看是否存在解决了这个问题。那个或者在睡眠循环之后调用GC.KeepAlive(timerEvery5);,因为该调用使变量保持un-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);