One timer vs three timers

I have a question about using System.Timers.Timer in my .NET applications.

I have three different events, each of which fires every second, and the other fires every minute, and the last fires every half hour.

Is it better, in terms of performance, to have one timer or three?

The way to do this with a single timer is to check ElapsedEventArgs ' SignalTime and compare it with the previously measured time. Of course, this does not work if you changed the DateTime, but that is not a problem. Basically, every second when it passes, I check if a minute or half an hour has passed ...

My concern is that using 3 timers creates too much overhead. Am I mistaken and should I use 3 for simplicity and clarity, or is one timer enough?

code:

 private void TimerEverySecondElapsed(object sender, ElapsedEventArgs e) { timerEverySecond.Enabled = false; OnTimerElapsed(TimerType.EverySecond); // Raise an event every minute if ((e.SignalTime - previousMinute) >= minuteSpan) { OnTimerElapsed(TimerType.EveryMinute); previousMinute = e.SignalTime; } // Raise an event every half hour if ((e.SignalTime - previousHalfhour) >= semiHourSpan) { OnTimerElapsed(TimerType.EverySemiHour); previousHalfhour = e.SignalTime; } timerEverySecond.Enabled = true; } 

minuteSpan and semiHourSpan are readonly TimeSpans.

+4
source share
3 answers

It will not make much difference anyway. Regardless of the number of timers in the background, only one cycle occurs. With this least efficient you will use 3 threads from the thread pool, but there are many available, so this is not a big deal. If this makes your code easier to read, I would say go for it.

Remember that this only applies to Threading.Timer (AKA Timers.Timer ). Forms.Timer behaves differently, and it would probably be better to just stick to one of them, since it only works with the user interface thread, so you may run into some synchronization issues.

Threading.Timer vs. Forms.Timer

Some additional resources:

http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/f9a1c67d-8579-4baa-9952-20b3c0daf38a/

How many instances of System.Timers.Timer can I create? How far can I scale?

+4
source

3 Timers add very little overhead compared to 1, and the code is likely to be much better (in terms of readability and maintainability)

0
source

I think that checking with if is more overhead than three timers, in addition, you may encounter some strange situations when trying to use one timer.

I would go with three timers.

0
source

All Articles