您的位置:首页 > 其它

Timer控件使用(System.Timers.Timer)

2015-08-22 09:29 369 查看
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()

  {

    //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事件停止(即隐去的内容),然后再次绑定
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: