System.Threading.Timer


using System.Threading;
using System.Windows.Forms;

/// <summary>
/// 
/// Timer(TimerCallback callback, object state, uint duetime, uint period)
/// duetime:回调首次被调用之前的时间,如果被设置为Timeout.Infinite则会停止计时
/// period:两次回调之间的时间间隔,如果被设置为Timeout.Infinite则回调只调用一次
///
/// </summary>
namespace test
{
    public partial class Form1
    {
        System.Threading.Timer timer;
        int count;
        TextBox textBox1;

        //创建计时器和每秒要执行的方法:
        Form1()
        {
            timer = new System.Threading.Timer(st =>
            {
                ++count;
                textBox1.AppendText("计数:" + count.ToString() + "\n");
                if (count == 100)
                    timer.Change(Timeout.Infinite, Timeout.Infinite);
            }, null, Timeout.Infinite, Timeout.Infinite);

            // 或(callback是执行函数):
            timer = new System.Threading.Timer(callback, null, 1000, 500); //(毫秒)
        }


        private void Callback(Object state)
        {
            // 执行操作,执行完归零计时器,回调callback,如此循环
            timer.Change(1000, 500);
        
            //  启动
            textBox1.AppendText("开始\n");
            count = 0;
            timer.Change(0, 1000);
            
            // 暂停
            timer.Change(Timeout.Infinite, Timeout.Infinite);
            
            // 继续
            timer.Change(0, 1000);
            
            // 停止
            timer.Change(Timeout.Infinite, Timeout.Infinite);
            count = 0;
        }
    }
}

 

class Program
{
   int TimesCalled = 0;
   void Display(object state)
   {
     Console.WriteLine("{0} {1} keep running.", (string)state, ++TimesCalled);
   }
   static void Main(string[] args)
   {
     Program p = new Program();
     //2秒后第一次调用,每1秒调用一次
     System.Threading.Timer myTimer = new System.Threading.Timer(p.Display, "Processing timer event", 2000, 1000);
     // 第一个参数是:回调方法,表示要定时执行的方法,第二个参数是:回调方法要使用的信息的对象,或者为空引用,第三个参数是:调用 callback 之前延迟的时间量(以毫秒为单位),指定 Timeout.Infinite 以防止计时器开始计时。指定零 (0) 以立即启动计时器。第四个参数是:定时的时间时隔,以毫秒为单位

     Console.WriteLine("Timer started.");
     Console.ReadLine();
   }
}

 


posted on 2020-05-24 13:37  jshchg  阅读(869)  评论(0编辑  收藏  举报

导航