开发者

Why is does my stopwatch keep reseting after 1 second

开发者 https://www.devze.com 2023-03-31 14:24 出处:网络
So I have the following code block: var sw = new Stopwatch(); sw.Start(); while (sw.Elapsed.Seconds<10)

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!


you need the TotalMilliseconds property of sw.Elapsed, instead of sw.Elapsed.Milliseconds


You do not necessarily need to use the TimeSpan returned by the Elapsed property.

StopWatch exposes an ElapsedMilliseconds property directly that returns the total number of milliseconds as a long. Going through the Elapsed property to get TotalMilliseconds will yield a double. Use the value that makes most sense to you.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号