C# 定時器Timer的執行個體介紹

來源:互聯網
上載者:User
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;                    }                }            }        }    }

  

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.