我可以用一个定时器来更新标签每x毫秒(Can I use a timer to update a l

2019-06-28 07:13发布

这是我的代码:

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

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

Answer 1:

你不能在一个紧凑的循环一样,更新用户界面,因为在UI线程运行的代码,它没有响应油漆事件 。 你可以做坏事一样“的DoEvents()”,但请不要......这将是更好的只是有一个Timer ,并定期更新UI时,计时器事件触发; 每50ms将是绝对速度最快的我走了,亲自。



Answer 2:

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

即使计时器是不准确的,然后StopWatch(..)它给你一个很好的控制。

只是例子sniplet:

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

   private void TimerEventProcessor(...){          
     label1.Text = "...";
   }


Answer 3:

这是一个WinForms应用程序?

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

您可以在这里添加一个快速和“脏”的解决方案(如有的WinForms)。 修改你的循环是这样的:

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

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



Answer 4:

如果你想让它第二次更新每次可以使用模运算在while循环:

Stopwatch timer = new Stopwatch();

timer.Start();

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

timer.Stop();

模数运算符给出了除法运算的剩余部分,如果几个毫秒的1000的倍数,将返回0。

我可能会考虑使用Timers 。 您使用上述技术,因此可能导致您的用户界面无响应做了很多纺纱



文章来源: Can I use a timer to update a label every x milliseconds