DispatcherTimer和Timer的區別


兩者區別是 Timer在非UI線程跑的,DispatcherTimer是在UI線程跑的,

DispatcherTimer 可以直接更新UI

Timer必須使用this.Dispatcher.BeginInvoke去更新UI        

private void DisPatcherTimerMethod()

        {
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(1000);
            timer.Tick += Timer_Tick;
            timer.Start();
        }
        private void Timer_Tick(object sender, EventArgs e)
        {
            this.label1.Text = DateTime.Now.ToString();
        }
        private void TimerMethod()
        {
            System.Timers.Timer tmr = new System.Timers.Timer(1000); //1秒一個循環
            tmr.Elapsed += tmr_Elapsed;
            tmr.Start();
        }
        private void tmr_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            this.Dispatcher.BeginInvoke(new Action(() =>
            {
                this.label2.Text = DateTime.Now.ToString();
            }), null);
        }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM