C#定时器使用

  • C#定时器使用已关闭评论
  • 88 次浏览
  • A+
所属分类:.NET技术
摘要

在C#里关于定时器类就有3个  
1.定义在System.Windows.Forms里  
2.定义在System.Threading.Timer类里  
3.定义在System.Timers.Timer类里

在C#里关于定时器类就有3个  
1.定义在System.Windows.Forms里  
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,完全取代上面的Timer控件。它们的缺点是不支持直接的拖放,需要手工编码。

例1:
使用System.Timers.Timer类

System.Timers.Timer t = new System.Timers.Timer(10000);//实例化Timer类,设置间隔时间为10000毫秒; t.Elapsed += new System.Timers.ElapsedEventHandler(theout);//到达时间的时候执行事件; t.AutoReset = true;//设置是执行一次(false)还是一直执行(true); t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件; public void theout(object source, System.Timers.ElapsedEventArgs e) {      MessageBox.Show("OK!"); }  

例2:

System.Threading.Timer类的TimerCallback 委托
System.Threading.Timer 是一个使用回调方法的计时器,而且由线程池线程服务,简单且对资源要求不高。
只要在使用 Timer,就必须保留对它的引用。对于任何托管对象,如果没有对 Timer 的引用,计时器会被垃圾回收。即使 Timer 仍处在活动状态,也会被回收。当不再需要计时器时,请使用 Dispose 方法释放计时器持有的资源。
使用 TimerCallback 委托指定希望 Timer 执行的方法。计时器委托在构造计时器时指定,并且不能更改。此方法不在创建计时器的线程中执行,而是在系统提供的线程池线程中执行。
创建计时器时,可以指定在第一次执行方法之前等待的时间量(截止时间)以及此后的执行期间等待的时间量(时间周期)。可以使用 Change 方法更改这些值或禁用计时器。
Demo application:
应用场景:在windows form程序自动执行某项工作后,希望其windows form能够自动关闭。

代码设计:

(1)首先声明Timer变量:private System.Threading.Timer timerClose;
(2)在上述自动执行代码后面添加如下Timer实例化代码:

// Create a timer thread and start it timerClose = new System.Threading.Timer(new TimerCallback(timerCall), this, 5000, 0);  

Timer构造函数参数说明:
Callback:一个 TimerCallback 委托,表示要执行的方法。
State:一个包含回调方法要使用的信息的对象,或者为空引用(Visual Basic 中为 Nothing)。
dueTime:调用 callback 之前延迟的时间量(以毫秒为单位)。指定 Timeout.Infinite 以防止计时器开始计时。指定零 (0) 以立即启动计时器。
Period:调用 callback 的时间间隔(以毫秒为单位)。指定 Timeout.Infinite 可以禁用定期终止。

(3)定义TimerCallback委托要执行的方法:

private void timerCall(object obj) {       timerClose.Dispose();       this.Close(); } 

当然,除了使用上述System.Threading.Timer类的TimerCallback 委托机制外,应该还有很多其他的办法。另外,这里只是demo了TimerCallback委托的简单应用。

......