The periodic timer stops unexpectedly after 61 runs

The next straightforward periodic timer (which should run ad-infinitum) stops immediately after 61 runs. The same is true if I switch 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 this on several 64-bit Windows 8 systems with .Net 4.5. The program compiles and runs from the shell. Is this a mistake or am I missing something?

+6
source share
1 answer

I believe that your timer receives garbage collection as a result of optimizing the runtime and determines that the timerEvery5 variable no longer refers to the method ... Try setting it to a static variable and see if it fixes the issue. This or call GC.KeepAlive(timerEvery5); AFTER a sleep cycle, as this call retains the un-GC'd variable until a method is executed (sort of unintuitive).

EDIT: from this link: http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx see the first example, as this is a similar problem. Quote from an 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); 
+9
source

Source: https://habr.com/ru/post/953649/


All Articles