The following straight-forward periodic timer (which should run ad-infinitum), stops just after 61 runs. The same is true if I change to .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);
}
I tried it on a couple of Windows 8 64-bit systems with .Net 4.5. The program is compiled and run from the command shell. Is it a bug or am I missing something?
I believe your timer is getting garbage collected as a result of the runtime optimizing and determining that the timerEvery5
variable is no longer being referenced in the method... Try setting it to a static variable and see if it fixes the issue. That or call GC.KeepAlive(timerEvery5);
AFTER the sleep loop, since that call keeps the variable un-GC'd until the method is executed (sort of unintuitive).
EDIT: per this link: http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx see the first example as it is a similar issue. A quote from the example:
// 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With