wpf(C#)定时器的使用方法

来源:赵克立博客 分类: WPF 标签:WPF发布时间:2017-08-12 13:55:17最后更新:2017-08-12 14:02:44浏览:3584
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2017-08-12 14:02:44
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章


c#中有四种定时器


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);

使用:


private static System.Windows.Threading.DispatcherTimer readDataTimer = new System.Windows.Threading.DispatcherTimer();
readDataTimer.Tick += new EventHandler(timeCycle);
readDataTimer.Interval = new TimeSpan(0, 0, 0, 1);
readDataTimer.Start();
public static void timeCycle(object sender, EventArgs e)
{
}



需要注意的是在wpf中涉及到界面操作的话,一定要使用第四种定时器DispatcherTime,DispatcherTimer是为wpf专门设计的,不然的话会提示界面资源被其他线程所拥有而无法更新界面。



微信号:kelicom QQ群:215861553 紧急求助须知
Win32/PHP/JS/Android/Python