Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Periodic timer stops unexpectedly, after 61 runs

Tags:

c#

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?

like image 709
user2770141 Avatar asked Sep 11 '13 19:09

user2770141


1 Answers

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);
like image 163
Haney Avatar answered Sep 30 '22 16:09

Haney