C#Timer

C#有两个命名空间下用到了Timer:

 较常用的是前者,代码如下,TimerHander是定时器时间到时执行的函数。

               System.Timers.Timer t = new System.Timers.Timer(1800000);//实例化Timer类,设置时间间隔  ms
               t.Elapsed += new System.Timers.ElapsedEventHandler(TimerHander);//到达时间的时候执行事件
               t.AutoReset = true;//设置是执行一次(false)还是一直执行(true)
               t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件

关闭定时器:给个变量,要关闭定时器的时候使其为真

        // yy 定时器函数
        void TimerHander(object source, ElapsedEventArgs e)
       {
           if (IsStopTest == true)
           {
               ((System.Timers.Timer)source).Stop();
               IsStopTest = false;
           }
      .....//执行语句
    }

关闭定时器不一定要在定时器处理函数内部,关键看定时器对象实例化的位置。

原文地址:https://www.cnblogs.com/fyp7077/p/7512217.html