C#倒计时器

The*_*ask 11 .net c# datetime winforms countdown

我正在尝试使用C#进行倒计时并以格式显示时间:

hour:minutes:seconds
Run Code Online (Sandbox Code Playgroud)

我试过这个:

 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!"; 
  }
Run Code Online (Sandbox Code Playgroud)

还出现了解决这个问题的不同方法.提前致谢

Cod*_*aos 29

你不应该Thread.Sleep在这里使用.Thread.Sleep在UI线程上阻塞UI,并且在另一个线程上使用它会导致由于线程同步而产生的额外复杂性.

如果您有C#5或异步CTP,您可能可以编写与您所做的非常相似的代码,因为您可以获得基于延续的等效Thread.Sleep,但不会阻止UI.

在标准C#4中我会使用a 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;
Run Code Online (Sandbox Code Playgroud)

在计时器处理程序中,您编写:

TimeSpan remainingTime=endTime-DateTime.UtcNow;
if(remainingTime<TimeSpan.Zero)
{
   label1.Text = "Done!";
   timer1.Enabled=false; 
}
else
{
  label1.Text = remainingTime.ToString();
}
Run Code Online (Sandbox Code Playgroud)

有关其他格式设置选项,请参阅标准TimeSpan格式字符串.

此代码仍然存在的一个问题是,如果系统时钟发生变化,它将无法正常工作.

当使用DateTime.Now而不是DateTime.UtcNow它时,在从/到夏令时切换或更改时区时也会中断.由于您要识别某个特定时间点(而不是显示时间),因此应使用UTC而不是本地时间.

  • @Rahul我的最后一段已经解决了这个问题.如果您的代码在夏令时打开/关闭"DateTime.Now"时会运行一个小时.然后有更多的哲学原因,我认为在与当地时间合作时,"DateTime"的设计并不是很好,所以我尽可能地避免使用它们. (2认同)

Jon*_*röm 6

我会使用像这样的计时器.首先是几个实例变量.

private int _countDown = 30; // Seconds
private Timer _timer;
Run Code Online (Sandbox Code Playgroud)

并在构造函数或加载事件中

_timer = new Timer();
_timer.Tick += new EventHandler(timer_Tick);
_timer.Interval = 1000;
_timer.Start();
Run Code Online (Sandbox Code Playgroud)

然后最后是事件处理程序

void timer_Tick(object sender, EventArgs e)
{
    _countDown--;
    if (_countDown < 1)
    {
        _countDown = 30;
    }
    lblCountDown.Text = _countDown.ToString();
}
Run Code Online (Sandbox Code Playgroud)