我想用 C# 制作一个简单的倒计时应用程序作为示例。
对于第一个基本版本,我使用标签显示当前剩余时间(以秒为单位),并使用按钮开始倒计时。 Button 的 Click-Event 是这样实现的:
private void ButtonStart_Click(object sender, RoutedEventArgs e)
{
_time = 60;
while (_time > 0)
{
_time--;
this.labelTime.Content = _time + "s";
System.Threading.Thread.Sleep(1000);
}
}
现在,当用户单击按钮时,时间实际上会倒计时(因为应用程序会卡住(由于 Sleep()))所选的时间量,但不会刷新标签的上下文。
我是不是做了一些普遍错误的事情(当涉及到线程时),还是只是 UI 的问题?
感谢您的回答! 我现在使用 System.Windows.Threading.DispatcherTimer 来按照你告诉我的去做。一切正常,所以这个问题得到了正式回答;)
对于那些感兴趣的人:这是我的代码(基本部分)
public partial class WindowCountdown : Window
{
private int _time;
private DispatcherTimer _countdownTimer;
public WindowCountdown()
{
InitializeComponent();
_countdownTimer = new DispatcherTimer();
_countdownTimer.Interval = new TimeSpan(0,0,1);
_countdownTimer.Tick += new EventHandler(CountdownTimerStep);
}
private void ButtonStart_Click(object sender, RoutedEventArgs e)
{
_time = 10;
_countdownTimer.Start();
}
private void CountdownTimerStep(object sender, EventArgs e)
{
if (_time > 0)
{
_time--;
this.labelTime.Content = _time + "s";
}
else
_countdownTimer.Stop();
}
}
最佳答案
是的,事件处理程序不应该阻塞——它们应该立即返回。 您应该通过 Timer、BackgroundWorker 或 Thread(按此优先顺序)实现它。
关于C# 简单倒计时-我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/942207/