目录
C# / .Net中的四种定时器:
1、System.Threading.Timer
2:System.Timers.Timer
3:System.Windows.Forms.Timer(Windows Forms Timer)
4:System.Windows.Threading.DispatcherTimer(WPF timer);
C# / .Net中的四种定时器:
System.Windows.Forms.Timer类型(Winfrom专用)
System.Threading.Timer类型
System.Timers.Timer类型
System.Windows.Threading.DispatcherTimer类型(WPF专用)
**************************************************************************************************************
1、System.Threading.Timer
private System.Threading.Timer timerClose;
timerClose = new System.Threading.Timer(new TimerCallback(timerCall), this, 5000, 0);private void timerCall(object obj)
{timerClose.Dispose();this.Close();
}
2: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;
//需要调用 timer.Start()或者timer.Enabled = true来启动它, timer.Start()的内部原理还是设置timer.Enabled = true;public void theout(object source, System.Timers.ElapsedEventArgs e)
{}
3:System.Windows.Forms.Timer(Windows Forms Timer)
System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();myTimer.Tick += new EventHandler(timer1_Tick);
myTimer.Enabled = true;
myTimer.Interval = 1000;
myTimer.Start();private void timer1_Tick(object sender, EventArgs e)
{
}
4:System.Windows.Threading.DispatcherTimer(WPF timer);
public DispatcherTimer SysInTimer = new System.Windows.Threading.DispatcherTimer();
SysInTimer.Tick += new EventHandler(Srcinf);
SysInTimer.Interval = TimeSpan.FromSeconds(15);
SysInTimer.Start();public void Srcinf(object sender, EventArgs e)
{}
注意的是在wpf中涉及到界面操作的话,一定要使用第四种定时器DispatcherTime,DispatcherTimer是为wpf专门设计的,不然的话会提示界面资源被其他线程所拥有而无法更新界面。
**************************************************************************************************************