0

I'm encountering a weird bug that seems to boil down to Task.Delay or System.Threading.Sleep not waiting the full interval specified, is this normal behaviour?

System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew();
//System.Threading.Thread.Sleep(ms); 
Task.Delay(ms).Wait();
var elapsed = sw.Elapsed.TotalMilliseconds;
if (elapsed < ms) {
    Console.WriteLine("WTF?");
}
  • Neither method is going to be accurate enough for precise timing. From the `Task.Delay` docs: "This method depends on the system clock. This means that the time delay will approximately equal the resolution of the system clock if the delay argument is less than the resolution of the system clock, which is approximately 15 milliseconds on Windows systems." See also: https://stackoverflow.com/questions/8815895/why-is-thread-sleep-so-harmful – Broots Waymb May 14 '19 at 20:12
  • 1
    Your code works as expected when run in dotnet fiddle. What delay are you using and what are you seeing for `elapsed`? – iakobski May 14 '19 at 20:14
  • Also, `Stopwatch` isn't a precision instrument. – Ron Beyer May 14 '19 at 20:19
  • With requesting a delay of 30ms I'm getting a elapsed time of 29.946800000000003, very close but the logic later on requires datetimes comparing datetimes and it is making a date_before > date_after, I can code around it but I'm just a little surprised neither call waits for a minumum of the delay specified, is there a timer that does? – Joe Gallagher May 14 '19 at 20:50
  • Its unrealistic to expect `Thread.Sleep` or `Task.Delay` to have that kind of precision, you might be better with some sort of spin lock – TheGeneral May 14 '19 at 23:24

0 Answers0