Timer more reliable than System.Threading.Timer

2019-04-26 04:52发布

问题:

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.

回答1:

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.



回答2:

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.



标签: c# .net timer