Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I efficently use timers

Tags:

c#

.net

timer

I have some Objects that Expire after a certain amount of time. Right now I am using a Single timer to raise an event every 10 seconds and run thru the object collection and see if anything has expired.

Instead of this I am considering adding a timer to each object and setting it to fire an event to expire at the desired time. I think the most appropriate timer is the System.Timers.Timer Does any one have any thoughts on this?

I have a test rig so I will be able to compare what I have now and the refactored implementation but I would like to think this is a good idea before I start.

like image 906
Noel Avatar asked Sep 14 '25 04:09

Noel


2 Answers

I wouldn't create that many timers, because of the overhead it would be.

Perhaps it's better to have one timer. Now this timer shouldn't trigger every 10 seconds, it should trigger when the next element expires. so you have some kind of "just in time trigger"

If you have 200 elements and the first will expire in 2 seconds, you could have a timer of 2 seconds regardless that the last element will expire in 2 years or so...

like image 127
Boas Enkler Avatar answered Sep 16 '25 19:09

Boas Enkler


I do prefer System.Threading.Timer over the one you mentioned. The reason is that System.Timers.Timer will consume all unhandled exceptions and therefore hide errors in your application.

I would also make a list of objects and traverse it in the timer method. It's a sound approach and not very hard to implement (Keep It Simple and Stupid)

The only reason to not do so is if it's important that the objects are check after exactly 10 seconds (and not 11 or 12 seconds). It all depends on how long each execution takes.

like image 40
jgauffin Avatar answered Sep 16 '25 18:09

jgauffin