我可以使用计时器每隔x毫秒更新一次标签

这是我的代码:

Stopwatch timer = new Stopwatch(); timer.Start(); while (timer.ElapsedMilliseconds < 3000) { label1.Text = Convert.ToString( timer.ElapsedMilliseconds ); } timer.Stop(); 

我的意思是实时更新标签的文本,所以如果timer.ElapsedMilliseconds == 1350 ,那么label1.Text = 1350 。 我怎样才能做到这一点? 提前致谢!

您不能像这样在紧密循环中更新UI,因为当UI线程正在运行该代码时,它不会响应绘制事件 。 你可以做一些讨厌的事情,比如“DoEvents()”,但请不要……最好只有一个Timer并在定时器事件触发时定期更新UI; 个人而言,每50毫秒将是我走的绝对最快。

你最好使用System.Windows.Forms.Timer ,而不是Stopwatch()

即使那个计时器不太精确,那么StopWatch(..)它也能给你一个很好的控制。

只是示例sniplet:

  myTimer.Tick += new EventHandler(TimerEventProcessor); myTimer.Interval = 1350; myTimer.Start(); private void TimerEventProcessor(...){ label1.Text = "..."; } 

这是一个WinForms应用程序吗?

问题是,当你的循环运行时,它不会给任何其他任务(比如更新GUI)任何可能性,所以GUI将更新整个循环完成。

您可以在此处添加快速且“脏”的解决方案(如果是WinForms)。 像这样修改你的循环:

 while (timer.ElapsedMilliseconds < 3000) { label1.Text = Convert.ToString( timer.ElapsedMilliseconds ); Application.DoEvents(); } 

现在标签应该在循环运行之间更新。

如果您希望每秒更新一次,可以在while循环中使用模数运算符:

 Stopwatch timer = new Stopwatch(); timer.Start(); while (timer.ElapsedMilliseconds < 3000) { if (timer.ElapsedMilliseconds % 1000 == 0) { label1.Text = timer.ElapsedMilliseconds.ToString(); } } timer.Stop(); 

模数运算符给出除法运算的余数,如果毫秒是1,000的倍数,它将返回0。

我可能会考虑使用Timers 。 您使用上述技术进行了大量旋转 ,这可能会导致您的UI无响应。