C#作的计时器

来源:互联网 发布:梦里花落知多少作者 编辑:程序博客网 时间:2024/05/16 15:25

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace 计时器
{   
    class TimerExamplState
    {
        public int counter = 0;
        public Timer tmr;
    }
    class Program
    {
        static void CheckStatus(object state)
        {
            TimerExamplState s = (TimerExamplState)state;
            s.counter++;
            Console.WriteLine("{0}Checking Status {1}",DateTime.Now.TimeOfDay,s.counter);
            if(s.counter==5)
            {
                (s.tmr).Change(1000,2000);
                Console.WriteLine("Changed.........");
                //Console.WriteLine("disposing of timer.....");
                //s.tmr.Dispose();
                //s.tmr = null;
            }
            if (s.counter == 10)
            {
                //(s.tmr).Change(1000, 1000);
                //Console.WriteLine("Changed.......");
                Console.WriteLine("disposing of timer.....");
                s.tmr.Dispose();
                s.tmr = null;
            }
        }   
        static void Main(string[] args)
        {
            TimerExamplState s = new TimerExamplState();
            TimerCallback timerDelegate = new TimerCallback(CheckStatus);
            Timer timer = new Timer(timerDelegate,s,1000,1000);
            s.tmr = timer;
            while (s.tmr != null)
                Thread.Sleep(0);
            Console.WriteLine("Timer finished!");
            Console.ReadKey();
        }
    }

}

原创粉丝点击