C# 計時器用法(DispatcherTimer、System.Timers.Timer、System.Threading.Timer)

首先,我以爲三種計時器最大的區別是:DispatcherTimer觸發的內容會直接轉到主線程去執行(耗時操做會卡住主線程),另外兩個則是在副線程執行,若是須要修改界面,則須要手動轉到主線程。api

DispatcherTimer:異步

        DispatcherTimer _timer;
        public void TestDispatcherTimer()
        {
            _timer = new DispatcherTimer();
            _timer.Interval = TimeSpan.FromSeconds(1);
            _timer.Tick += _timer_Tick;
            _timer.Start();
        }
        private void _timer_Tick(object sender, EventArgs e)
        {
            try 
            {
                Trace.WriteLine("Test DispatcherTimer");
                _timer.Stop();
            }
            catch (Exception ex)
            {
                Trace.WriteLine("Error");
                _timer.Stop();
                _timer.Start();
            }
        }        

System.Timers.Timer:spa

        System.Timers.Timer _timer;
        public void TestTimersTimer()
        {
            _timer = new System.Timers.Timer();
            _timer.Interval = 1000; //單位毫秒
            _timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);
            _timer.Start();
        }

        private void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                Trace.WriteLine("Test System.Timers.Timer");
                #region 此處展現的是把副線程的內容轉到主線程
                System.Windows.Application.Current.Dispatcher.Invoke(
                         new Action(() =>
                         {
                             Trace.WriteLine("同步切換");
                         }));
                System.Windows.Application.Current.Dispatcher.BeginInvoke(
                         new Action(() =>
                         {
                             Trace.WriteLine("異步切換");
                         }));
                #endregion
                _timer.Stop();
            }
            catch (Exception ex)
            {
                Trace.WriteLine("Error");
                _timer.Stop();
                _timer.Start();
            }
        }

System.Threading.Timer:線程

        System.Threading.Timer _timer;
        private void TeseThreadingTimer()
        {
            _timer = new System.Threading.Timer(new System.Threading.TimerCallback(Out), null, 0, 1000); //各參數意思詳見:https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.timer?redirectedfrom=MSDN&view=netframework-4.8
        }
        private void Out(object sender)
        {
            try
            {
                Trace.WriteLine("Test System.Threading.Timer");
            }
            catch (Exception ex)
            {
                Trace.WriteLine("Error");
            }
        }
        private void Stop()
        {
            _timer.Dispose();
        }

 此處我的無關記載:Environment.TickCount code

相關文章
相關標籤/搜索