Is it normal behaviour that Stopwatch can return negative values? Code sample below can be used to reproduce it.
while (true) { Stopwatch sw = new Stopwatch(); sw.Start(); sw.Stop(); if (sw.ElapsedMilliseconds < 0) Debugger.Break(); }
The only place where I can reproduce negative numbers is my virtual machine (hosted by Hyper-V on a 8-core machine)
By default, the elapsed time value of a Stopwatch instance equals the total of all measured time intervals. Each call to Start begins counting at the cumulative elapsed time; each call to Stop ends the current interval measurement and freezes the cumulative elapsed time value.
This is a bug. It doesn't seem to have a lot of attention around it, through, so I'd suggesting following up with that report.
The uninspiring workaround appears to be to ignore negative values:
long elapsedMilliseconds = Math.Max(0, stopwatch.ElapsedMilliseconds);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With