C# 定时器Timer_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > C# 定时器Timer

C# 定时器Timer

 2017/6/10 5:32:43  1390193352  程序员俱乐部  我要评论(0)
  • 摘要:staticvoidMain(string[]args){#region定时器TimerDemotd=newTimerDemo("TimerDemo",1000);td.Enabled=true;td.TickEvent+=TestHandler;Threadtimer=newThread(td.Run);timer.Start();#endregionConsole.ReadLine();}///<summary>///测试用事件///</summary>
  • 标签:C#
class="brush:csharp;gutter:true;">static void Main(string[] args)
        {
            #region  定时器
            TimerDemo td = new TimerDemo("TimerDemo", 1000);
            td.Enabled = true;
            td.TickEvent += TestHandler;
            Thread timer = new Thread(td.Run);
            timer.Start();
            #endregion
            Console.ReadLine();
        }

        /// <summary>
        /// 测试用事件
        /// </summary>
        static void TestHandler()
        {
            Console.WriteLine(DateTime.Now.ToLongTimeString());
        }

  

public class TimerDemo
    
    {
        //线程名
        string _ThreadName;
        public string ThreadName
        {
            get { return _ThreadName; }
            private set { _ThreadName = value; }
        }
        //时间间隔
        int _TimeInterval;
        public int TimeInterval
        {
            get { return _TimeInterval; }
            set { _TimeInterval = value; }
        }
        //当前计时器是否启用 true:启用 false:不启用
        bool _Enabled;
        public bool Enabled
        {
            get { return _Enabled; }
            set { _Enabled = value; }
        }
        //每隔一段时间需要运行的事件
        public delegate void TickEventHandler();
        public event TickEventHandler TickEvent;
        /// <summary>
        /// 建立一个计时器(构造函数)
        /// </summary>
        /// <param name="ThreadName">线程名</param>
        /// <param name="TimeInterval">时间间隔</param>
        public TimerDemo(string ThreadName, int TimeInterval = int.MaxValue)
        {
            this.ThreadName = ThreadName;
            this.TimeInterval = TimeInterval;
            this.Enabled = false;
        }
        /// <summary>
        /// 定期执行事件
        /// </summary>
        public void Run()
        {
            while (true)
            {
                //如果当前计时器并未启用,则每隔一段时间检测是否被启用
                if (!this.Enabled)
                {
                    Thread.Sleep(100);
                    continue;
                }
                //触发事件TickEvent
                if (TickEvent != null)
                {
                    TickEvent();
                }
                //休眠一定的时间,等待下一个循环
                Thread.Sleep(TimeInterval % 100);
                for (int temp = 0; temp < TimeInterval / 100; temp++)
                {
                    Thread.Sleep(100);
                    if (!this.Enabled)
                    {
                        break;
                    }
                }
            }
        }
    }

  

发表评论
用户名: 匿名