Timer 异步定时器

  class Program
    {
        int TimesCalled = 0;
        /// <summary>
        /// 回调方法
        /// </summary>
        /// <param name="state"></param>
        void Display(object state)
        {
            //这里是子线程
            Console.WriteLine("当前线程Display=" + Thread.CurrentThread.ManagedThreadId.ToString());


            Console.WriteLine("{0} {1}", (string)state, ++TimesCalled);
        }
        static void Main(string[] args)
        {
            Console.WriteLine("当前线程Main=" + Thread.CurrentThread.ManagedThreadId.ToString());


            Program p = new Program();
            ///TimerCallback callback回调方法
            /// object state 参数
            /// int dueTime  调用 callback 之前延迟的时间量(以毫秒为单位)
            /// int period 执行间隔
            //public Timer(TimerCallback callback, object state, int dueTime, int period);
            Timer myTimer = new Timer(p.Display, "Processing timer event", 2000, 2000);
            Console.WriteLine("Timer started.");
            Thread.Sleep(1000);
            myTimer.Dispose();
            Console.ReadKey();
        }
    }

猜你喜欢

转载自blog.csdn.net/luochenlong/article/details/80255395