c#倒计时计时器
本文关键字:计时器 倒计时 | 更新日期: 2023-09-27 18:13:06
我正在尝试使用c#制作一个倒计时,并以格式显示时间:
hour:minutes:seconds
我试过了:
var minutes = 3; //countdown time
var start = DateTime.Now;
var end = DateTime.Now.AddMinutes(minutes);
Thread.Sleep(1800);
if (??) // I tried DateTime.Now > end not works
{
//... show time
label1.Text = "...";
}
else
{
//done
label1.Text = "Done!";
}
解决这个问题的不同方法也出现了。提前感谢
此处不应使用Thread.Sleep
。UI线程上的Thread.Sleep
阻塞UI,并且在另一个线程上使用它会由于线程同步而导致额外的复杂性。
如果你有c# 5或异步CTP,你可能可以编写与你所做的非常相似的代码,因为这样你就得到了一个基于Thread.Sleep
的延续,而不会阻塞UI。
在标准c# 4中,我将使用System.Windows.Forms.Timer
。
开始倒计时:
var minutes = 3; //countdown time
var start = DateTime.UtcNow; // Use UtcNow instead of Now
endTime = start.AddMinutes(minutes); //endTime is a member, not a local variable
timer1.Enabled = true;
在计时器处理程序中:
TimeSpan remainingTime=endTime-DateTime.UtcNow;
if(remainingTime<TimeSpan.Zero)
{
label1.Text = "Done!";
timer1.Enabled=false;
}
else
{
label1.Text = remainingTime.ToString();
}
有关其他格式化选项,请参阅标准时间跨度格式字符串。
这段代码仍然存在的一个问题是,如果系统时钟改变,它将无法正常工作。
当使用DateTime.Now
而不是DateTime.UtcNow
时,它也会在从/切换到夏令时或更改时区时中断。由于您想要识别某个时间点(而不是显示时间),因此应该使用UTC而不是本地时间。
我会像这样使用计时器。首先是几个实例变量。
private int _countDown = 30; // Seconds
private Timer _timer;
和在构造函数或加载事件
中_timer = new Timer();
_timer.Tick += new EventHandler(timer_Tick);
_timer.Interval = 1000;
_timer.Start();
最后是事件处理程序
void timer_Tick(object sender, EventArgs e)
{
_countDown--;
if (_countDown < 1)
{
_countDown = 30;
}
lblCountDown.Text = _countDown.ToString();
}
您还可以使用Timer,因为这将处理所有问题,如ui锁定。您可以使用System.Windows.Forms.Timer
-Timer。在MSDN库中,您可以找到使用它的示例。
WinForms-Timer还处理跨timer线程和ui线程的调用。
——SeriTools
您的代码设置了变量,然后进入睡眠状态3分钟,因此if语句在离开睡眠状态之前不会执行。要么建立一个新线程来更新UI,要么做类似这样的事情…
while (DateTime.now < end) {
label1.Text = "...";
Thread.Sleep(#); //Pick a second, or 5 or whatever
}
label1.Text = "Done!";
有了第二个线程,你仍然可以在程序工作的时候做一些事情。完成后会显示"Done!"