So I have the following code block:
var sw = new Stopwatch();
sw.Start();
while (sw.Elapsed.Seconds<10)
{
System.Threading.Thread.Sleep(50);
Console.WriteLine(sw.Elapsed.Milliseconds.ToString() + " ms");
}
sw.Stop();
and in the output I have
50 ms
101 ms
151 ms
202 ms
253 ms
304 ms
355 ms
405 ms
456 ms
507 ms
558 ms
608 ms
659 ms
710 ms
761 ms
812 ms
862 ms
913 ms
964 ms
15 ms
65 ms
116 ms
167 ms
218 ms
Why does it reset every 1000 ms? I need to wait for 10 seconds and I can’t use Thread.Sleep(10000); because this 3rd party library i use sleeps also and I need it to do stuff during that time.
Because
Stopwatch.Elapsed.Millisecondsjust outputs the milliseconds component of the elapsed time. It is not the total time in milliseconds. This is clear from the documentation.Stopwatch.Elapsedis an instance ofTimeSpanandTimeSpan.Millisecondsstates:If you want the output in milliseconds, and you want the total milliseconds, then use
TimeSpan.TotalMilliseconds:always, Always, ALWAYS check the documentation!