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.Milliseconds
just outputs the milliseconds component of the elapsed time. It is not the total time in milliseconds. This is clear from the documentation. Stopwatch.Elapsed
is an instance of TimeSpan
and TimeSpan.Milliseconds
states:
Gets the milliseconds component of the time interval represented by the current
TimeSpan
structure.
If you want the output in milliseconds, and you want the total milliseconds, then use TimeSpan.TotalMilliseconds
:
Gets the value of the current
TimeSpan
structure expressed in whole and fractional milliseconds.
always, Always, ALWAYS check the documentation!
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