Timer控件使用(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;

//调用 timer.Stop()或者timer.Enabled = false来停止引发Elapsed事件, timer.Stop()的内部原理还是设置timer.Enabled = false,最重要的是timer.Enabled = false后会取消线程池中当前等待队列中剩余任务的执行。

举例:

class timerExample

{

  int num = 0;

  //IUSObject blinkObj=null;

  System.Timers.Timer t = null;

  public  static  void  Init()

  {

    //if(blinkObj !=null)

    //{

    //  num = 1;

    //  blinkObj.Visible = true;

    //  t.Enable = false;

    //}

    //blinkObj = new IUSObject();

    t = new System.Timers.Timer(1000);

    t.Elapsed += new System.Timers.ElapsedEventHandler(willDo);  

    t.AutoReset = true;  

    t.Enabled = true;

  }

  public  static void  willDo(object sender, System.Timers.ElapsedEventArgs e)

  {

    //blinkObj.Visible = blinkObj.Visible == true ? false : true;

    MessageBox.Show("每隔1000毫秒执行一次");

     

    if(num>=6)

    {

      System.Timers.Timer  t  = (System.Timers.Timer)sender;

      t.Enable = false;

    }

    num += 1;

  }

}

 说明:若要指定timer的循环次数,需通过num辅助 执行,多次执行Init时,需先将timer的elapsed事件停止(即隐去的内容),然后再次绑定

 

随笔记录一下,若能帮到大家,很荣幸,帮不到也莫责怪。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM