The timer takes 10 ms longer than the interval

I use a timer with an interval of 1 second. But in the timer event, when I print the time, always 62 or 65 ms. I do not understand why it takes 10 ms more.

Please can someone take a look at this.

Here is the code I'm using:

static int _counter;
var _timer = new System.Timers.Timer(1000);
public Form1()
{
    InitializeComponent();           
    _timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
    _timer.Start();            
}

private void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
    Console.WriteLine(DateTime.Now.ToString("{hh:mm:ss.fff}"));          
    _counter++;
    if (_counter == 20)
        _timer.Stop();
}

And this conclusion:

{01:59:08.381}
{01:59:09.393}
{01:59:10.407}
{01:59:11.421}
{01:59:12.435}
{01:59:13.449}
{01:59:14.463}
{01:59:15.477}
{01:59:16.491}
{01:59:17.505}
{01:59:18.519}
{01:59:19.533}
{01:59:20.547}
{01:59:21.561}
{01:59:22.575}
{01:59:23.589}
{01:59:24.603}
{01:59:25.615}
{01:59:26.629}
{01:59:27.643}
+3
source share
11 answers

, Windows . , , , , , , - , .

Windows " ", . , , , . (, ) . , . Windows , , .

- -, 50 , / .

+15

- . , .

+6

-, , 1 , 50 .

-, . . , , , , , . , , , , .

+4

, Win32, ( 1 ). CodeProject , #.

+4

, , . , , , . . Timer, , .
, , .

+2

, . .

+1

System.Timers.Timer . , , .

, , .

static int _counter;
        System.Timers.Timer _timer = new System.Timers.Timer(1000);
        Stopwatch sw;
        public Form1()
        {
            InitializeComponent();           
            _timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
            _timer.Start();            
            sw = Stopwatch.StartNew();
        }

        void _timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            Console.WriteLine(sw.ElapsedMilliseconds);          
            _counter++;
            if (_counter == 20)
                _timer.Stop();            

            sw.Reset();
            sw.Start();
        }
+1

14 . googled; .

+1

, Windows . Windows, Win CE Windows Embedded.

-S

+1

, . , , , , , , . , , , , .

+1

, RTOS ( ). , :

Program.MicroTimer microTimer = new Program.MicroTimer();
microTimer.MicroTimerElapsed += new Program.MicroTimer.MicroTimerElapsedEventHandler(OnTimedEvent);
microTimer.Interval = 1000; // Call micro timer every 1000µs (1ms)

// Can choose to ignore event if late by Xµs (by default will try to catch up)
// microTimer.IgnoreEventIfLateBy = 500; // 500µs (0.5ms)

microTimer.Enabled = true; // Start timer
System.Threading.Thread.Sleep(2000);
microTimer.Enabled = false;

. .

0

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


All Articles