System.Diagnostics.Stopwatch returns negative numbers in Elapsed... properties

c#, stopwatch

Solution

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);

Problem

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)

Original source