Large Number of Timers

.net, c#, timer

Solution

You should do it the simplest way possible. If you are concerned about performance, you should run your application through a profiler and determine the bottlenecks. You might be very surprised to find out it was some code which you least expected, and you had optimized your code for no reason. I always write the simplest code possible as this is the easiest. See PrematureOptimization

I don't see why there would be any pitfalls with a large number of timers. Are we talking about a dozen, or 100, or 10,000? If it's very high you could have issues. You could write a quick test to verify this.

As for which of those Timer classes to use: I don't want to steal anyone elses answer who probably did much more research: check out this answer to that question`

Problem

I need to write a component that receives an event (the event has a unique ID). Each event requires me to send out a request. The event specifies a timeout period, which to wait for a response from the request. If the response comes before the timer fires, great, I cancel the timer. If the timer fires first, then the request timed out, and I want to move on. This timeout period is specified in the event, so it's not constant. The expected timeout period is in the range of 30 seconds to 5 minutes. I can see two ways of implementing this. - Create a timer for each event and put it into a dictionary linking the event to the timer. - Create an ordered list containing the DateTime of the timeout, and a new thread looping every 100ms to check if something timed out. Option 1 would seem like the easiest solution, but I'm afraid that creating so many timers might not be a good idea because timers might be too expensive. Are there any pitfalls when creating a large number of timers? I suspect that in the background, the timer implementation might actually be an efficient implementation of Option 2. If this option is a good idea, which timer should I use? System.Timers.Timer or System.Threading.Timer. Option 2 seems like more work, and may not be an efficient solution compared to Option 1. Update The maximum number of timers I expect is in the range of 10000, but more likely in the range of 100. Also, the normal case would be the timer being canceled before firing. Update 2 I ran a test using 10K instances of `System.Threading.Timer` and `System.Timers.Timer`, keeping an eye on thread count and memory. `System.Threading.Timer` seems to be "lighter" compared to `System.Timers.Timer` judging by memory usage, and there was no creation of excessive number of threads for both timers (ie - thread pooling working properly). So I decided to go ahead and use `System.Threading.Timer`.

Original source

Related problems