I have code similar to this
mTestModeMetadataTimer = new System.Threading.Timer(SomeTimerCallback, null, 1000, Timeout.Infinite);
Stopwatch tmStopwatch = new Stopwatch();
private void SomeTimerCallback(object state)
{
Console.WriteLine("{0}: SomeTimerCallback time: {1}", System.Threading.Thread.CurrentThread.ManagedThreadId, tmStopwatch.ElapsedMilliseconds);
tmStopwatch.Restart();
mTestModeMetadataTimer.Change(990, Timeout.Infinite);
}
Everything works fine, except sometimes there is a huge delay between timer events, as shown in this console output.
31: SomeTimerCallback time: 998
21: SomeTimerCallback time: 997
20: SomeTimerCallback time: 999
3: SomeTimerCallback time: 989
3: SomeTimerCallback time: 1000
3: SomeTimerCallback time: 994
37: SomeTimerCallback time: 999
3: SomeTimerCallback time: 991
29: SomeTimerCallback time: 1002
37: SomeTimerCallback time: 1000
3: SomeTimerCallback time: 17568
3: SomeTimerCallback time: 999
29: SomeTimerCallback time: 993
This is a small part of a fairly significant application. The same behavior existed using System.Timers.Timer and, in fact, occurs at different points in time throughout the application. I added a thread id to the console output of this timer, in order to hopefully get a little more information about why there was a random 17.5 second time between the right events in one second.
Is there something that I'm obviously doing wrong? Perhaps there is some more data that I can collect to understand why my timers work funny?
Any suggestions here would be greatly appreciated.