I need to create some windows service which will execute every some often, every hour. The question is - which timer control should I use: System.Timers.Timer or System.Threading.Timer one? I am asking because I have been reading through the forum and I am getting a few mixed reviews on both. Also, the explanations are kind of hard to follow as I am pretty new to programming. Thank you.
Asked
Active
Viewed 952 times
0
-
1Please note that you actually might want to use a scheduled task instead of using a service to do regularly repeating tasks. – Dirk Vollmar May 09 '11 at 15:42
2 Answers
1
Read @Jon Skeet's Timers write-up: http://www.yoda.arachsys.com/csharp/threads/timers.shtml

MikeM
- 27,227
- 4
- 64
- 80
0
I use System.Timers.Timer in my Windows services. It's easy to control and hook up. VS 2010's Intellisense even creates the elapsed event handler as you type "myTimer.Elapsed += ..."
You can also stop the timer at the beginning of your event handler and restart it at the end if you don't want the timer firing before the event handler is finished on long-running processing. For example:
System.Timers.Timer myTimer;
void Main()
{
myTimer = new System.Timers.Timer(1000);
myTimer.Elapsed += new System.Timers.ElapsedEventHandler(myTimer_Elapsed);
myTimer.Start();
}
void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
myTimer.Stop();
// process event
myTimer.Start();
}

Ed Power
- 8,310
- 3
- 36
- 42
-
Could you step through wait this chunk of code is doing? I believe that I understand it but I am not totally sure. Does this say for every sec do what function/code is placed where "// process event" is? Thank you. – LaDante Riley May 10 '11 at 19:23
-
@Dante - myTimer will call myTimer_Elapsed one second after myTimer.Start(). Once inside myTimer_Elapsed, myTimer is stopped, your processing code is executed (whatever you want to happen when the timer fires), and then myTimer is restarted. You don't have to stop and start the timer each timer each time you handle the elapsed event if your processing is done before the next interval occurs. – Ed Power May 10 '11 at 23:34