0

I made a small funktion at a console app (.net 4.5.2) to check the exactness of the timeout at the AutoResetEvent.WaitOne funktion. On my laptop the waited time is almost exact the timeout at WaitOne (right picture). On every other system I had run this test, the timeout is mutch higher (left picture). I tried to update .net but without any change.

Is this different behavior related to a special hardware (Lenovo p52) of me, or I am using visual studio?

private static void WaitTest()
{
    try
    {
        using (var lResetEvent = new AutoResetEvent(false))
        {
            _stopwatch.Restart();
            lResetEvent.WaitOne(1);
            var l1Ms = _stopwatch.ElapsedMilliseconds;
            _stopwatch.Restart();
            lResetEvent.WaitOne(10);
            var l10Ms = _stopwatch.ElapsedMilliseconds;
            _stopwatch.Restart();
            lResetEvent.WaitOne(20);
            var l20Ms = _stopwatch.ElapsedMilliseconds;

            Console.WriteLine($"-----------------------------------------------------------");
            Console.WriteLine($" 1ms WaitTest: {l1Ms:D2}ms");
            Console.WriteLine($"10ms WaitTest: {l10Ms:D2}ms");
            Console.WriteLine($"20ms WaitTest: {l20Ms:D2}ms");
            Console.WriteLine($"-----------------------------------------------------------");
        }
    }
    catch (Exception lEx)
    {
        Console.WriteLine(lEx.ToStringEx());
    }
}

enter image description here

user2029101
  • 116
  • 9
  • 1
    If you're referring to the different delay times, you might want to google `timeBeginPeriod` for some background information. – 500 - Internal Server Error Feb 26 '21 at 13:21
  • 1
    I expect it's for the same reason that timer granularity isn't great - it's based on the accuracy of the system clock. But that's not mentioned in that documentation. [Timer.Interval](https://learn.microsoft.com/en-us/dotnet/api/system.timers.timer.interval?view=net-5.0) shows how to measure the accuracy. – Damien_The_Unbeliever Feb 26 '21 at 13:21
  • You can precisely measure elapsed time interval in .NET, but when you want to do nothing for arbitrary amount of time things are not so good. Whatever way you choose it will be pretty innacurate and you will never achieve such precision. – Alexey Rumyantsev Feb 26 '21 at 13:28

1 Answers1

0

If you're referring to the different delay times, you might want to google timeBeginPeriod for some background information. – 500 - Internal Server Error

leads me her: how to set timer resolution from C# to 1 ms?

This is doing the job now:

 using (new TimePeriod(1))
    lResetEvent.WaitOne(WaitTime);

The timer resolution seems not to effect the AutoResetEvent. Its alwaysaroud 15ms:

        [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool GetSystemTimeAdjustment(out long lpTimeAdjustment, out long lpTimeIncrement, out bool lpTimeAdjustmentDisabled);
user2029101
  • 116
  • 9