关于C#中的Timer

翻译|其它|编辑:郝浩|2007-12-10 14:19:07.000|阅读 1663 次

概述:

# 界面/图表报表/文档/IDE等千款热门软控件火热销售中 >>

关于 C#中 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 控件。它们的缺点是不支持直接的拖放,需要手工编码。

例:
使用 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!");
}


Form 中的应用起来就更简单了

使用 Timer 类可以定时触发你所定义的方法。本文介绍使用 Timer 类的具体步骤


using System.Threading;
using System.Timers;

1 创建计时器的新实例:

System.Windows.Form.Timer aTimer = new System.Windows.Form.Timer();

2 指定事件处理程序:
aTimer.Tick += new EventHandler(OnTimer);

3 指定引发事件的频率:
aTimer.Interval = 1000;

4 启用组件:

aTimer.Enabled = true;

5 处理事件:
public static void OnTimer(Object source, EventArgs e) {
      Console.WriteLine("Hello World!");
}


标签:

本站文章除注明转载外,均为本站原创或翻译。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,如果存在内容上的异议请邮件反馈至chenjj@evget.com

文章转载自:个人博客

为你推荐

  • 推荐视频
  • 推荐活动
  • 推荐产品
  • 推荐文章
  • 慧都慧问
扫码咨询


添加微信 立即咨询

电话咨询

客服热线
023-68661681

TOP