簡述System.Windows.Forms.Timer 與System.Timers.Timer用法區別

來源:互聯網
上載者:User

標籤:time   art   定時器   程式假死   lap   stop   UI   sum   應用   

System.Windows.Forms.Timer

  基於表單應用程式

  阻塞同步 

  單線程

  timer中處理時間較長則導致定時誤差極大。

System.Timers.Timer 

  基於服務

  非阻塞非同步

  多線程

        /// <summary>        /// windows定時器        /// </summary>        System.Windows.Forms.Timer _wTimer;        /// <summary>        /// 應用程式產生定時器        /// </summary>        System.Timers.Timer _tTimer;                private void Form1_Load(object sender, EventArgs e)        {            _wTimer = new System.Windows.Forms.Timer();            _wTimer.Interval = 500;//設定時間間隔500毫秒            _wTimer.Tick += _wTimer_Tick;            _wTimer.Start();//啟動定時器            _tTimer = new System.Timers.Timer();            _tTimer.Interval = 500;//設定時間間隔500毫秒            _tTimer.Elapsed += _tTimer_Elapsed;            //_tTimer.Start();        }        void _tTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)        {            Print("_tTimer_Elapsed" + _count.ToString());            Thread.Sleep(2000);//休眠2秒            _count++;        }        void _wTimer_Tick(object sender, EventArgs e)        {            Print("_wTimer_Tick" + _count.ToString());            Thread.Sleep(2000);//休眠2秒            _count++;        }        private void Print(string msg)        {            if (this.InvokeRequired)            {                this.BeginInvoke((Action)delegate()                 {                    textBox1.AppendText(msg + "\r\n");                });            }            else            {                textBox1.AppendText(msg + "\r\n");            }        }

當啟動_wTimer.Start(),輸出結果。在_wTimer_Tick 休眠2秒阻塞主線程,導致程式假死2秒。而且事件沒在沒有處理完成不會進行下次,所以_count 結果每次只輸出一次、

 

當啟動_tTimer.Start(),每隔500毫秒添加一個線程。由於非同步只要到達時間間隔則自動產生下個線程,不管上個線程是否處理完成。

所以_count的結果會有多次輸出。

 

如果想解決 system.timers 沒到時間間隔只產生一個線程或者說上次沒有處理完下次則等待處理可以在處理前添加_tTimer.stop(),完成後再次啟動_tTimer.start()。

 

簡述System.Windows.Forms.Timer 與System.Timers.Timer用法區別

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.