C# 中有三种计时器,分别是:
System.Windows.Forms.Timer
System.Threading.Timer
System.Timers.Timer
System.Windows.Forms.Timer 只能试用在Windows窗体程序中,不能用于控制台程序,且为单线程
private void Form1_Load(object sender, EventArgs e)
{
System.Windows.Forms.Timer time = new System.Windows.Forms.Timer();
time.Tick += Time_Tick;
time.Interval = 1000; // 间隔1s 执行一次Time_Tick方法
time.Start();
}
private void Time_Tick(object sender, EventArgs e)
{
string str = DateTime.Now.ToString()+ " Timer 线程ID=" + Thread.CurrentThread.ManagedThreadId.ToString() + "\n";
richTextBox1.Text = richTextBox1.Text + str;
Thread.Sleep(2000);
}
运行结果为下图,因为该计时器仅支持单线程,所以指定Time_Tick方法执行时间是1s,但由于方法中出现了Thread.Sleep(2000),使得每2s输出一次信息
System.Threading.Timer 相同能用于任何程序中,且为多线程
class Program
{
static System.Threading.Timer timer;
static void Main(string[] args)
{
timer = new System.Threading.Timer(TimeCallBack, null, 0, 1000); // 代码-1
//timer = new System.Threading.Timer(TimeCallBack, null, 0, Timeout.Infinite); // 代码-2
Console.ReadKey();
}
private static void TimeCallBack(object state)
{
Console.WriteLine(DateTime.Now.ToString() + " Timer 线程ID=" + Thread.CurrentThread.ManagedThreadId.ToString());
Thread.Sleep(2000);
//timer.Change(1000, Timeout.Infinite); // 代码-3
//timer.Change(-1, Timeout.Infinite); // 代码-4
}
}
运行结果为下图(左),在timer实例化0s后,由一个线程(ID=6)执行TimeCallBack方法,由于Thread.Sleep(2000)原因,使得该线程2s后结束TimeCallBack方法,
但是由于设定的间隔时间是1s,而线程(ID=6)没有执行结束TimeCallBack方法,所以重新建立了线程(ID=12)执行TimeCallBack方法。
被注释 "代码-3" 1s后,只运行一次TimeCallBack方法, “代码-4”停止timer计时器
System.Timers.Timer 与 System.Threading.Timer 基本相同,只是使用方式有所差异
System.Timers.Timer time = new System.Timers.Timer(1000);
time.Elapsed += Time_Elapsed;
time.Enabled = true;
private static void Time_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
Console.WriteLine(DateTime.Now.ToString() + " Timer 线程ID=" + Thread.CurrentThread.ManagedThreadId.ToString());
Thread.Sleep(5000);
time.Enabled = false;
}