WPF中Timer與DispatcherTimer類的區別


前幾天在WPF中寫了一個軌跡回放的功能,我想稍微做過類似項目的,都曉得采用一個時間控件或者時間對象作為調度器,我在這么做的時候,出現了問題,於是將程序中的Timer換成了DispatchTimer,然后就可以了,特意在網上找了下這兩者的區別,看到一篇比較詳細的,並且有代碼的博文,我就直接引用了,原文地址:http://www.cnblogs.com/zhchbin/archive/2012/03/06/2381693.html,我只附加上原文的代碼。

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Timers; namespace TimerTest { /// <summary>
/// Interaction logic for MainWindow.xaml /// </summary>
    public partial class MainWindow : Window { private Timer aTimer = null; public MainWindow() { InitializeComponent(); aTimer = new Timer(); aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); // Set the Interval to 5 seconds.
            aTimer.Interval = 1000; aTimer.Enabled = true; aTimer.Start(); } private void OnTimedEvent(object source, ElapsedEventArgs e) { timeLabel.Content = DateTime.Now.ToUniversalTime(); } } }

 

 

using System; using System.Windows; using System.Timers; using System.Windows.Threading; namespace TimerTest { /// <summary>
/// Interaction logic for MainWindow.xaml /// </summary>
    public partial class MainWindow : Window { private Timer aTimer = null; private delegate void TimerDispatcherDelegate(); public MainWindow() { InitializeComponent(); aTimer = new Timer(1000); aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); aTimer.Interval = 1000; aTimer.Enabled = true; } private void OnTimedEvent(object sender, EventArgs e) { this.Dispatcher.Invoke(DispatcherPriority.Normal, new TimerDispatcherDelegate(updateUI)); } private void updateUI() { timeLabel.Content = DateTime.Now.ToUniversalTime(); } } }

通過這些,我想到,其實多線程訪問UI的都是相通的,在Winform中為了更新UI,我們都會有帶有Invoke或者委托來實現,而Timer要用來更新,主要看這個Timer是否多線程的。


免責聲明!

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



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