Friday, January 30, 2009

Threads in .Net

Working with Windows Services can be quite tricky. You can't debug them like a normal application or a .Net site, you have to attach a process to them once running. Also, one important thing to remember is if you have multiple timers firing at different times, if they and their callbacks are not on different threads, weird things can happen. I ran into this issue recently. There are two different Timer classes in .Net (that I'm aware of, there might be more). There is System.Timers.Timer and System.Threading.Timer. To ensure the events will be processed in different threads you must use System.Threading.Timer. It is very similar to System.Timers.Timer, but when you initialize the Threading Timer, you pass it the callback function, the object (to be passed to the callback function) or null, the start time, and the interval. You do not have to enable/disable the threading Timer like you do the Timers Timer. Once you initialize it and set it's callback function with interval, you're all set!

This may all seem pretty trival and it is, but for someone who is new to window's services and timers it is a very important distinction!

V

2 comments:

Timur said...

There are actually more three timer classes in .Net

Here's a good article
http://msdn.microsoft.com/en-us/magazine/cc164015.aspx

Vanessa aka V Sixx said...

Yea, I actually found that out after I posted. So much to learn!