为什么我的秒表在 1 秒后不断重置

发布于 2024-12-02 06:14:33 字数 544 浏览 2 评论 0原文

所以我有以下代码块:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

十级心震 2024-12-09 06:14:33

因为 Stopwatch.Elapsed.Milliseconds 只输出经过时间的毫秒部分。它不是以毫秒为单位的总时间。从文档中可以清楚地看出这一点。 Stopwatch.ElapsedTimeSpanTimeSpan.Milliseconds 状态:

获取当前 TimeSpan 结构表示的时间间隔的毫秒部分。

如果您想要以毫秒为单位的输出,并且想要总毫秒数,请使用 TimeSpan。总毫秒数

获取当前 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 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!

陌若浮生 2024-12-09 06:14:33

您需要 TotalMilliseconds sw.Elapsed 的属性,而不是 sw.Elapsed.Milliseconds

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

祁梦 2024-12-09 06:14:33

您不一定需要使用 Elapsed 属性返回的 TimeSpan

StopWatch 直接公开一个 ElapsedMilliseconds 属性,该属性以 long 形式返回总毫秒数。通过 Elapsed 属性获取 TotalMilliseconds 将产生一个双精度值。使用对您来说最有意义的值。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文