如何在C#中使秒表显示秒和毫秒?
问题描述:
所以我想去做一个定时器,做这样的:每次我点击出现这种情况的按钮:如何在C#中使秒表显示秒和毫秒?
0.052
0.521
1.621
2.151
.. 。
但不是,它是这样的:
0.015
0.032
0.112
0.252
...
这是发生: picture
此代码是不正确的,我等待了很长时间,直到它使一个秒。
int sec = 0, ms = 1;
private void button1_Click(object sender, EventArgs e)
{
timer1.Start();
listBox1.Items.Add(label1.Text);
timer1.Interval = 1;
}
private void timer1_Tick(object sender, EventArgs e)
{
ms++;
if (ms >= 1000)
{
sec++;
ms = 0;
}
label1.Text = String.Format("{0:0}.{1:000}", sec, ms);
}
答
您应该从.NET Framework的System.Diagnostics命名空间中使用一个秒表对象。就像这样:
System.Diagnostics.Stopwatch sw = new Stopwatch();
public void button1_Click()
{
sw.Start; // start the stopwatch
// do work
...
sw.Stop; // stop the stopwatch
// display stopwatch contents
label1.Text = string.Format({0}, sw.Elapsed);
}
如果你想看到经过的总秒数只有毫秒的总时间(不数分钟或数小时),您可以更改最后一行到:
label1.Text = string.Format({0}, sw.ElapsedMilliseconds/1000.0)
+1
或使用内插字符串'label1.Text = $“{sw.ElapsedMilliseconds/1000.0}”;' – flakes
+0
@flkes - 如果用户使用C#6,那么效果会很好。 – STLDeveloper
的GUI线程每秒更新'label1' 1000次?是的,不。使用更大的间隔。留出一些时间让线程完成绘画。 –
Windows上的默认计时器分辨率为15.6毫秒。 –
这只是一个表达错误,没有人对中介价值感兴趣。你有一个保证,你的用户界面每秒更新至少64次,这足以欺骗人的眼睛。只需更新标签,即可丢失列表框。如果你想让它精确到原子钟,那么使用实际的wallclock时间,因此调用你的Tick事件处理器的操作系统的任何延迟都不起作用。使用Environment.TickCount。 –