欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#基于TimeSpan实现倒计时效果的方法

程序员文章站 2023-12-18 11:12:34
本文实例展示了c#基于timespan实现倒计时效果的方法,比较实用的功能,对于初学者来说有一定的学习参考价值。具体实现方法如下: 示例代码如下: using...

本文实例展示了c#基于timespan实现倒计时效果的方法,比较实用的功能,对于初学者来说有一定的学习参考价值。具体实现方法如下:

示例代码如下:

using system;
using system.threading;

namespace consoleapplication29
{
  class program
  {
    static void main(string[] args)
    {
      try
      {
        datetime _timeend = datetime.now.addseconds(62);
        threadpool.queueuserworkitem((arg) =>
        {
          timespan _ts = _timeend - datetime.now;
          while (true)
          {
            thread.sleep(1000);
            if (_ts.totalseconds >= 0)
            {
              console.writeline("还剩余{0}分钟{1}秒", _ts.minutes, _ts.seconds);
              _ts = _ts.addseconds(-1);
            }
          }
        });
      }
      catch (exception ex)
      {
        console.writeline(ex.message);
      }
      finally
      {
        console.readline();
      }
    }
  }
  public static class timespantoolv2
  {
    public static timespan addseconds(this timespan ts, int seconds)
    {
      return ts.add(new timespan(0, 0, seconds));
    }
    public static timespan addminutes(this timespan ts, int minutes)
    {
      return ts.add(new timespan(0, minutes, 0));
    }
    public static timespan addhours(this timespan ts, int hours)
    {
      return ts.add(new timespan(hours, 0, 0));
    }
  }
}

代码运行效果如下:

C#基于TimeSpan实现倒计时效果的方法

上一篇:

下一篇: