C#/WPF,几种定时器的使用与介绍


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); //0天0时0分1秒进行刷新一次
    readDataTimer.Start();  
      
    public static void timeCycle(object sender, EventArgs e)  
    {  
      
    }  

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值