C#倒计时 [英] C# countdown timer

查看:339
本文介绍了C#倒计时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用C#来进行倒计时,并显示格式的时间:

I'm trying to make a countdown using C# and show the time in format:

hour:minutes:seconds

我已经试过这样:

I've tried this:

 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!"; 
  }

不同的方法来解决这个问题也出现了。在此先感谢

Different ways to solve this problem also appeared. Thanks in advance

推荐答案

您不应使用 Thread.sleep代码在这里。 Thread.sleep代码在UI线程块的用户界面,并用它在另一个线程导致额外的复杂性,由于线程同步。

You should not use Thread.Sleep here. Thread.Sleep on the UI thread blocks the UI, and using it on another thread leads to additional complexity due to thread synchronization.

如果您有C#5或异步CTP你大概可以写code非常相似,你做了什么,因为你再得到一个延续基于相当于 Thread.sleep代码不阻止用户界面。

If you have C# 5 or the async CTP you probably can write code very similar to what you did, since you then get a continuation based equivalent of Thread.Sleep that doesn't block the UI.

在标准C#4我会使用一个<一个href="http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx"><$c$c>System.Windows.Forms.Timer.

In standard C# 4 I'd use 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;

在定时器处理程序中这样写:

In the timer handler you write:

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

有关其他格式化选项见标准时间跨度格式字符串的。

For other formatting options see Standard TimeSpan Format Strings.

一个问题是保持与此code是它不会正确如果系统时钟的变化工作。

One issue that remains with this code is that it will not work correctly if the system clock changes.

在使用 DateTime.Now 而不是 DateTime.UtcNow 从/切换到夏令时,它也将打破或更改时区。既然你要确定一个特定的时间点(而不是显示时间),你应该使用,而不是本地时间UTC。

When using DateTime.Now instead of DateTime.UtcNow it will also break when switching from/to daylight saving or changing the timezone. Since you want to identify a certain point in time (and not a display time) you should use UTC instead of local time.

这篇关于C#倒计时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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