刚写C#时,使用Timer比较多的是System.Windows.Forms.Timer。这个控件使用起来比较简单一些,它直接继承自Component。在使用时,TImer控件绑定Tick时间,开始计时采用Timer.Start()或者TImer.enable=True后才会自定计时,停止时候采用TImer.stop()或者Timer.enable=false。在开始之前,需要设置一下Timer.Interval=100(时间间隔ms)。Timer控件和它所在的Form属于同一个线程,因此执行效率不是很高,不如新开一个线程采用system.Threading.Timer。
using System;using System.Windows.Forms;using System.Threading;namespace WindowsFormsApplication13{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { timer1.Interval = 1000; timer1.Start(); } private void timer1_Tick(object sender, EventArgs e) { textBox1.Text = DateTime.Now.ToShortDateString(); } }}
- 需要回调的对象
- 要传入给委托的参数,null表示没有参数
- 延时多久开始执行
- 每隔几秒执行一次
public void TestTimerCallBack() { TimerCallback tc = new TimerCallback((o) => { MessageBox.Show("Do something"); }); System.Threading.Timer t = new System.Threading.Timer(tc, null, 0, 1000); }
再加入一个比较经典的用法:
using System;using System.Collections.Generic;using System.Text;using System.Threading;namespace TimerApp{ class Program { static void Main(string[] args) { Console.WriteLine("***** Working with Timer type *****/n"); // Create the delegate for the Timer type. TimerCallback timeCB = new TimerCallback(PrintTime); // Establish timer settings. Timer t = new Timer( timeCB, // The TimerCallback delegate type. "Hello From Main", // Any info to pass into the called method (null for no info). 0, // Amount of time to wait before starting. 1000); //一秒钟调用一次 Interval of time between calls (in milliseconds). Console.WriteLine("Hit key to terminate..."); Console.ReadLine(); } static void PrintTime(object state) { Console.WriteLine("Time is: {0}, Param is: {1}", DateTime.Now.ToLongTimeString(), state.ToString()); } }}