为什么我的秒表在 1 秒后不断重置
所以我有以下代码块:
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();
在输出中我有
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
为什么它每 1000 毫秒重置一次?我需要等待 10 秒,并且无法使用 Thread.Sleep(10000); 因为我使用的这个第 3 方库也会休眠,并且我需要它在这段时间里做一些事情。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为 Stopwatch.Elapsed.Milliseconds 只输出经过时间的毫秒部分。它不是以毫秒为单位的总时间。从文档中可以清楚地看出这一点。
Stopwatch.Elapsed
是TimeSpan
和TimeSpan.Milliseconds
状态:如果您想要以毫秒为单位的输出,并且想要总毫秒数,请使用
TimeSpan。总毫秒数
:总是,总是,总是检查文档!
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 ofTimeSpan
andTimeSpan.Milliseconds
states:If you want the output in milliseconds, and you want the total milliseconds, then use
TimeSpan.TotalMilliseconds
:always, Always, ALWAYS check the documentation!
您需要
TotalMilliseconds
sw.Elapsed
的属性,而不是sw.Elapsed.Milliseconds
you need the
TotalMilliseconds
property ofsw.Elapsed
, instead ofsw.Elapsed.Milliseconds
您不一定需要使用
Elapsed
属性返回的TimeSpan
。StopWatch
直接公开一个ElapsedMilliseconds
属性,该属性以long
形式返回总毫秒数。通过Elapsed
属性获取TotalMilliseconds
将产生一个双精度值。使用对您来说最有意义的值。You do not necessarily need to use the
TimeSpan
returned by theElapsed
property.StopWatch
exposes anElapsedMilliseconds
property directly that returns the total number of milliseconds as along
. Going through theElapsed
property to getTotalMilliseconds
will yield a double. Use the value that makes most sense to you.