【发布时间】:2009-06-02 22:21:29
【问题描述】:
我想用 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();
}
}
【问题讨论】:
标签: c# wpf multithreading