本文实例讲述了C#自定义基于控制台的Timer实现方法。分享给大家供大家参考。具体如下:
一、概述
这里实现了一个自定义类TimerTest,该类可以模拟一个Timer,经过指定时间间隔执行某个事件。
二、TimerTest类
//定时器类
class TimerTest
{
//线程名
string _ThreadName;
public string ThreadName
{
get { return _ThreadName; }
private set { _ThreadName = value; }
}
//时间间隔
int _TimeInterval;
public int TimeInterval
{
get { return _TimeInterval; }
set { _TimeInterval = value; }
}
//当前计时器是否启用 true:启用 false:不启用
bool _Enabled;
public bool Enabled
{
get { return _Enabled; }
set { _Enabled = value; }
}
//每隔一段时间需要运行的事件
public delegate void TickEventHandler();
public event TickEventHandler TickEvent;
///
/// 建立一个计时器(构造函数)
///
/// 线程名
/// 时间间隔
public TimerTest(string ThreadName, int TimeInterval = int.MaxValue)
{
this.ThreadName = ThreadName;
this.TimeInterval = TimeInterval;
this.Enabled = false;
}
///
/// 定期执行事件
///
public void Run()
{
while (true)
{
//如果当前计时器并未启用,则每隔一段时间检测是否被启用
if (!this.Enabled)
{
Thread.Sleep(100);
continue;
}
//触发事件TickEvent
if (TickEvent != null)
{
TickEvent();
}
//休眠一定的时间,等待下一个循环
Thread.Sleep(TimeInterval % 100);
for (int temp = 0; temp < TimeInterval / 100; temp++)
{
Thread.Sleep(100);
if (!this.Enabled)
{
break;
}
}
}
}
}
三、调用示例
每1000毫秒输出当前的时间
////// 测试用事件 /// static void TestHandler() { //TODO Console.WriteLine(DateTime.Now.ToLongTimeString()); } static void Main(string[] args) { TimerTest tt = new TimerTest("timer_test", 1000); tt.Enabled = true; tt.TickEvent += TestHandler; Thread timer = new Thread(tt.Run); timer.Start(); Console.ReadLine(); }
四、运行结果
希望本文所述对大家的C#程序设计有所帮助。



