Linux下使用c#开发倒计时功能

 在这里,我将采用两种线程方式开发倒计时功能,线程分别采用ThreadPool 和Thread。使用ThreadPool、Thread,需要先使用System.Threading空间。

 开发功能:下班倒计时(假设每天下午5:30下班)
1.首先我们需要获取离下班还有多长时间,这里我们采用TimeSpan来计算时间差。
String ymd = DateTime.Now.ToString("yyyy-MM-dd");
DateTime end = DateTime.ParseExact(ymd + " 17:30:00","yyyy-MM-dd HH:mm:ss",null);
DateTime start = DateTime.Now;
TimeSpan ts = end - start;
2.倒计时功能实现

    2.1 通过ThreadPool方式
ThreadPool.QueueUserWorkItem ((arg) => 
    {
        while(ts.Hours != 0 || ts.Minutes != 0 || ts.Seconds != 0){
            //timeTextViewer 是窗体中TextView的名称,我们将时间显示在窗体上
            timeTextViewer.Buffer.Text = 
            "离下班还剩  " + ts.Hours + " 小时 " + ts.Minutes + " 分钟 " + ts.Seconds + " 秒";
            Thread.Sleep(1000);
            ts = ts.Add(new TimeSpan(0,0,-1));
        }
    });
2.2 通过Thread方式
//在窗体创建的函数中:
Thread thread = new Thread (TimerLeft);
thread.Start ();

//函数外,同一类中
private void TimerLeft(){
    DateTime end = DateTime.ParseExact(ymd + " 17:30:00","yyyy-MM-dd HH:mm:ss",null);
    DateTime start = DateTime.Now;
    TimeSpan ts = end - start;
    while(ts.Hours != 0 || ts.Minutes != 0 || ts.Seconds != 0){
        timeTextViewer.Buffer.Text = 
        "离下班还剩  " + ts.Hours + " 小时 " + ts.Minutes + " 分钟 " + ts.Seconds + " 秒";
        Thread.Sleep(1000);
        ts = ts.Add(new TimeSpan(0,0,-1));
    }
}
完成后我们就可以运行我们的程序了。

这里写图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章