One Timer vs Three Timers Performance

I have a question about the usage of System.Timers.Timer in my .NET applications.

I have three different events, one triggers every second, another triggers every minute and the last one triggers every half hour.

Is it better, performance wise, to have one timer or three?

The way to do it with one timer is to check ElapsedEventArgs ' SignalTime and compare it to a previously measured time. Of course this doesn't quite work if you've changed the DateTime, but that's not the issue here. Basically every second it elapses I check whether a minute or a half hour has passed as well...

My concern is that using 3 timers creates too much overhead. Am I wrong and should I use 3 for simplicity and clarity or is 1 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.


It's not going to make much of a difference either way. Regardless of the number of timers there's only one loop going on in the background. At it's least efficient you will be using 3 threads from the thread pool but there are a lot available so it's not a big deal. If it makes your code simpler to read I'd say go for it.

Keep in mind however this only applies to Threading.Timer (AKA Timers.Timer ). Forms.Timer behaves a bit differently and it would probably would be better to just stick with one of those since it only operates on the UI thread so you may run into some sync issues.

Threading.Timer vs. Forms.Timer

Some More Resources:

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

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


3与1相比,定时器的开销增加很少,代码很可能会更好一些(在可读性和可维护性方面)


I think checks with if's are more of overhead than three timers, besides you can get in some weird situations trying to use one timer.

I'd go with three timers.

链接地址: http://www.djcxy.com/p/63020.html

上一篇: System.Timers.Timer逐渐增加间隔?

下一篇: 一个定时器与三个定时器的性能