以下直接定期计时器(应无限运行)在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);
}
Run Code Online (Sandbox Code Playgroud)
我在几台带有.Net 4.5的Windows 8 64位系统上试过它.该程序是从命令shell编译和运行的.这是一个错误还是我错过了什么?
我相信你的计时器正在通过运行时优化获得垃圾收集并确定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);
Run Code Online (Sandbox Code Playgroud)