Wednesday, July 13, 2011

Using a timer with a Windows service

When I write a Windows service I like to build a class library which I can test using a WinForms/WPF project; a test harness.  For me, its easier to debug this way than trying to attach to the process while running, etc.

I recently had a problem where my service ran perfectly except for some items I setup on a timer.  I couldn't find an error in the Event Log and when I tested the code in my test harness application it worked fine.  After adding a ton of logging I found that my timer never fired!

Ultimately what I found is that my test harness application's code (which I copied and pasted directly into my service to fire off my class library's methods) the timer was an instance of type System.Windows.Forms.Timer but my other services used System.Threading.Timer!  Changing the type of timer immediately solved my problem.

Moral of the story, make sure you're using the correct timer object!  The Windows.Forms.Timer will not work in anything outside of a form!