I'm currently using the System.Threading.Timer on a 10 second interval. I've adding a small piece of code to write to a file each time the timer fires, and whilst most of the time it fires on-time, sometimes (presumably when the rest of the app is buy), fails to fire for 30 or 40 seconds, and fires over and over again in quick succession.
Is there a more reliable timer I can use in .NET 3.5?
The timer is setup as follows
Timer someTimer = new Timer(new TimerCallback(SomeMethod), null, 0, 10000);
...and the callback is:
private static void SomeMethod(object state)
However, it's difficult to provide much more code than this, as the Timer usually fires correctly. When it's embedded in a massive application (~100,000 lines or so), with mulitple threads being fired off, left, right, and centre, you slowly start to see the timer firing intermitently. I've seen several posts suggesting the ThreadPool may be exhausted, so I'm currently looking in to see if this might be what I'm experiencing.
Timers. Timer is geared towards multithreaded applications and is therefore thread-safe via its SynchronizationObject property, whereas System.
Timers. Timer raises the elapsed event, is it raised in an independent thread? Yes, they run in a different thread. The System.
The Timer class (in the System. Threading namespace) is effective to periodically run a task on a separate thread. It provides a way to execute methods at specified intervals. This class cannot be inherited. This class is particularly useful for developing console applications, where the System.
Yes, it will create new threads.
Refer different timer classes in .net
There are three timer classes called 'Timer' in .NET. It sounds like you're using the Windows Forms one, but actually you might find the System.Threading.Timer class more useful - but be careful because it calls back on a pool thread, so you can't directly interact with your form from the callback.
More Accurate Timer - As per MSDN
The Windows Forms Timer component is single-threaded, and is limited to an accuracy of 55 milliseconds. If you require a multithreaded timer with greater accuracy, use the Timer class in the System.Timers namespace.
This sounds exactly like thread pool starvation. Look out for long running/blocking jobs running in the thread pool and either rewrite using async io, or in the case of long running CPU intensive jobs, simply don't run these jobs in the thread pool. Run them on their own thread or use a background worker.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With