C#-----定时器的几种实现
1. System.Windows.Forms.Timer
计时器最宜用于 Windows 窗体应用程序中,并且必须在窗口中使用,适用于单线程环境,
在此环境中, UI 线程用于执行处理。 它要求用户代码提供 UI 消息泵, 并且始终从同一线程操作, 或将调用封送到
其他线程。Windows 窗体计时器组件是单线程的, 且限制为55毫秒的准确度,准确性不高
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace TestTimer { public partial class frmTimerDemo : Form { private System.Windows.Forms.Timer timerGetTime; public frmTimerDemo() { InitializeComponent(); } 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(); } } }
2. System.Timers.Timer
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Timers; using System.Windows.Forms; namespace TimerDemo { public partial class frmTimerDemo : Form { private static System.Timers.Timer aTimer; public frmTimerDemo() { InitializeComponent(); } private void frmTimerDemo_Load(object sender, EventArgs e) { aTimer = new System.Timers.Timer(); aTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent); aTimer.Interval = 1000; aTimer.Enabled = true; aTimer.Start(); } public void OnTimedEvent(Object source, ElapsedEventArgs e) { this.labelTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); } private void frmTimerDemo_FormClosed(object sender, FormClosedEventArgs e) { aTimer.Stop(); } } }
3. System.Threading.Timer
线程计时器也不依赖窗体,是一种简单的、轻量级计时器,它使用回调方法而不是使用事件,并由线程池线程提供支持
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace TimerDemo { 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); Console.WriteLine("Timer started."); Console.ReadLine(); } } }