Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Threading.Timer not firing after some time

I have a windows service application. And debugging it by running in console mode.

Here http://support.microsoft.com/kb/842793 it is written that Timers.Timer has a bug and not firing in windows services. And workaround is to use Threading.Timer And this article is for .NET 1.0 and 1.1

I am using .NET 4 but after some time Threading.Timer also doesn't fire. So what can be the reason for this? And what can you suggest as a workaround?

Thanks,

Best Regards

EDIT: I changed timer from Threading.Timer to Timers.Timer and it is working without any problem.

like image 704
AFgone Avatar asked Sep 03 '10 12:09

AFgone


3 Answers

Are you keeping a reference to your timer somewhere to prevent it being garbage collected?

From the docs:

As long as you are using a Timer, you must keep a reference to it. As with any managed object, a Timer is subject to garbage collection when there are no references to it. The fact that a Timer is still active does not prevent it from being collected.

like image 186
Jon Skeet Avatar answered Nov 15 '22 05:11

Jon Skeet


Your timer object goes out of scope and gets erased by Garbage Collector after some time, which stops callbacks from firing.

Save reference to it in a member of class.

like image 34
Grozz Avatar answered Nov 15 '22 04:11

Grozz


Work around?

Personally, I suggest using a RegisterWaitForSingleObject function as opposed to timers for the exact reason you are running into. The RegisterWaitForSingleObject registers a delegate to be called on interval that you set analgous to a timer and are super easy to implement. You could have a test harness up and running in a matter of hours. I use this method of interval firing in my Windows Services and it is a tried and true stable solution that works for me.

Read the link below and goto the links within the article for code samples and walkthroughs.

Running a Periodic Process in .NET using a Windows Service:
http://allen-conway-dotnet.blogspot.com/2009/12/running-periodic-process-in-net-using.html

like image 39
atconway Avatar answered Nov 15 '22 06:11

atconway