The timer does not work accidentally

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)
{
    // doing minimal work here

    Console.WriteLine("{0}: SomeTimerCallback time: {1}", System.Threading.Thread.CurrentThread.ManagedThreadId, tmStopwatch.ElapsedMilliseconds);
    tmStopwatch.Restart();

    // Better to be on the safe side and do this slightly more than once per second, than slightly less.
    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.

+4
3

comment - . , 17,5 , .

, , , , ( System.Timers.Timer , ( , ) System.Windows.Forms.Timer )

+2

System.Threading.Timer , CLR. , , .

, , :

int workerThreads;
int completitionPortThreads;
System.Threading.ThreadPool.GetAvailableThreads(out workerThreads, out completitionPortThreads);
+2

Try periodically in the Timer constructor:

mTestModeMetadataTimer = new System.Threading.Timer(SomeTimerCallback, null, 1000, TimeSpan.FromMilliseconds(990));

Are you sure that you are not in debug mode, and you release the time before continuing?

0
source

Source: https://habr.com/ru/post/1542339/


All Articles