C#实现定时器的三种方案

在C#里关于定时器类就有三个

  1. System.Windows.Forms.Timer
  2. System.Threading.Timer
  3. 定义在System.Timers.Timer

下面对这三个类进行讲解。.

System.Windows.Forms.Timer是应用于WinForm中的,它是通过Windows消息机制实现的,类似于VB或Delphi中  的Timer控件,内部使用API SetTimer实现的。它的主要缺点是计时不精确,而且必须有消息循环,Console  Application(控制台应用程序)无法使用。

System.Timers.Timer和System.Threading.Timer非常类似,它们都是通过.NET  Thread  Pool实现的,轻量,计时精确,对应用程序、消息没有特别的要求。System.Timers.Timer还可以应用于WinForm,完全取代上面的System.Windows.Forms.Timer控件。

System.Windows.Forms.Timer

计时器最宜用于 Windows 窗体应用程序中,并且必须在窗口中使用,适用于单线程环境,

在此环境中, UI 线程用于执行处理。它要求用户代码提供 UI 消息泵, 并且始终从同一线程操作, 或将调用封送到

其他线程。Windows 窗体计时器组件是单线程的, 且限制为55毫秒的准确度,准确性不高

public partial class frmTimerDemo : Form
 {
 private System.Windows.Forms.Timer timerGetTime;

 private void frmTimerDemo_Load(object sender, EventArgs e)
 {
 //创建定时器
 timerGetTime = new System.Windows.Forms.Timer();
 //设置定时器属性
 timerGetTime.Tick+=new EventHandler(HandleTime);
 timerGetTime.Interval = 1000;
 timerGetTime.Enabled = true;
 //开启定时器
 timerGetTime.Start();
 }
 public void HandleTime(Object myObject, EventArgs myEventArgs)
 {
 labelTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
 }
 private void frmTimerDemo_FormClosed(object sender, FormClosedEventArgs e)
 {
 //停止定时器
 timerGetTime.Stop();
 }
 }

System.Timers.Timer

这个是目前我们定时项目中常用的。

System.Timers.Timer t = new System.Timers.Timer(10000);//实例化Timer类,设置间隔时间为10000毫秒;
t.Elapsed += new System.Timers.ElapsedEventHandler(Execute);//到达时间的时候执行事件;
t.AutoReset = true;//设置是执行一次(false)还是一直执行(true);
t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件;
t.Start(); //启动定时器
//上面初始化代码可以写到构造函数中 
public void Execute(object source, System.Timers.ElapsedEventArgs e)
{
 t.Stop(); //先关闭定时器
 MessageBox.Show("OK!");
t.Start(); //执行完毕后再开启器
}

这里需要注意的是Execute方法中一定要先关闭定时器,执行完毕后再开启。这个是本人经过测试的,如果你注释掉这两句,定时器会不断的执行Execute方法,如果Execute执行的是一个很耗时的方法,会导致方法未执行完毕,定时器又启动了一个线程来执行Execute方法。

System.Threading.Timer

线程计时器也不依赖窗体,是一种简单的、轻量级计时器,它使用回调方法而不是使用事件,并由线程池线程提供支持,先看下面代码

class Program
 {
 int TimesCalled = 0;
 void Display(object state)
 {
 Console.WriteLine("{0} {1} keep running.", (string)state, ++TimesCalled);
 }
 static void Main(string[] args)
 {
 Program p = new Program();
 //2秒后第一次调用,每1秒调用一次
 System.Threading.Timer myTimer = new System.Threading.Timer(p.Display, "Processing timer event", 2000, 1000);
 // 第一个参数是:回调方法,表示要定时执行的方法,第二个参数是:回调方法要使用的信息的对象,或者为空引用,第三个参数是:调用 callback 之前延迟的时间量(以毫秒为单位),指定 Timeout.Infinite 以防止计时器开始计时。指定零 (0) 以立即启动计时器。第四个参数是:定时的时间时隔,以毫秒为单位

 Console.WriteLine("Timer started.");
 Console.ReadLine();
 }
}

上面是c#定时器的集中方案,大家在使用中一定要尽量把定时器声明成静态(static),如果放在实例方法中,会导致实例对象被回收导致定时器失效。