我可以使用计时器每 x 毫秒更新一次标签吗 [英] Can I use a timer to update a label every x milliseconds

查看:28
本文介绍了我可以使用计时器每 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.我怎样才能做到这一点?提前致谢!

My intetion was to update the label's text in real time, so if timer.ElapsedMilliseconds == 1350, then label1.Text = 1350. How can I do this? Thanks in advance!

推荐答案

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

You cannot update the UI in a tight loop like that, because while the UI thread is running that code, it isn't responding to paint events. You can do nasty things like "DoEvents()", but please don't... it would be better to just have a Timer and update the UI periodically when the timer event fires; every 50ms would be the absolute fastest I'd go, personally.

这篇关于我可以使用计时器每 x 毫秒更新一次标签吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆