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

3 c# timer stopwatch

这是我的代码:

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

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

Tig*_*ran 9

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

即使该计时器不太准确,StopWatch(..)它也能为您提供良好的控制.

只是示例sniplet:

   myTimer.Tick += new EventHandler(TimerEventProcessor);       
   myTimer.Interval = 1350;
   myTimer.Start();

   private void TimerEventProcessor(...){          
     label1.Text = "...";
   }
Run Code Online (Sandbox Code Playgroud)


Mar*_*ell 5

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