本文实例为大家分享了C#线程倒计时器源码,供大家参考,具体内容如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace ListZZBG
{
class TimeHeleper
{
Thread thread;
private TimeSpan time; //计时时间
private TimeSpan endTime; //到点时间
private Label lb;
private bool whereExit = true;
/// <summary>
/// 设定计时器计时的时间
/// </summary>
/// <param name="StartTime">计时器时间,如:01:00:00 既1小时</param>
public TimeHeleper(TimeSpan StartTime, Label lb)
{
time = StartTime;
this.lb = lb;
}
public void ShowLabel()
{
lb.Text = time.ToString();
}
/// <summary>
/// 获取时间
/// </summary>
/// <returns></returns>
public TimeSpan GetTime()
{
return time;
}
/// <summary>
/// 开启计时器
/// </summary>
public void Open()
{
//计算到点时间
TimeSpan tsNow = TimeSpan.Parse(DateTime.Now.ToString("HH:mm:ss"));
TimeSpan tsAdd = time;
endTime = tsNow + tsAdd;
//线程开始
whereExit = false;
thread = new Thread(TimeThreadStart);
thread.IsBackground = true;
thread.Start();
}
/// <summary>
/// 关闭计时器
/// </summary>
public void Close()
{
whereExit = true;
thread.Join(1000);
}
private void TimeThreadStart()
{
while (!whereExit)
{
RunTime();
Thread.Sleep(1000);
}
}
private delegate void RunTimeDelegate();
private void RunTime()
{
if (lb.InvokeRequired)
{
RunTimeDelegate d = RunTime;
lb.Invoke(d);
}
else
{
time = endTime - TimeSpan.Parse(DateTime.Now.ToString("HH:mm:ss"));
string[] sp = time.ToString().Split(':');
lb.Text = sp[2].ToString(); //liable1控件
}
}
}
}
您可能感兴趣的文章:C#使用后台线程BackgroundWorker处理任务的总结C# FileStream实现多线程断点续传C#中的多线程超时处理实践方案C#多线程之Semaphore用法详解C# 文件上传下载(Excel导入,多线程下载)功能的实现代码C#多线程爬虫抓取免费代理IP的示例代码C#多线程之Thread类详解C#多线程之线程控制详解C#多线程ThreadPool线程池详解C#多线程中如何运用互斥锁Mutexc#中Winform实现多线程异步更新UI(进度及状态信息)C# 线程同步详解详解C#多线程之线程同步C#开启线程的四种方式示例详解