2010-02-13 137 views
21

请解释“DispatcherTimer”和“定期定时”是@Kent Boogaart意味着使用一个多线程WPF应用程序如本主题任务sheduler之间的区别:DispatcherTimer VS在WPF应用程序定期定时器任务调度

Advice needed for multi-threading strategy for WPF application

在评论

到后(报价)之一:

- 如果所有的DispatcherTimer确实是开球另一个线程,什么是使用DispatcherTimer点? ....那些线程并不需要在UI线程上启动。你可以只使用一个普通定时器和避免中断的UI完全

什么是“定期定时”是指什么?他们如何(“DispatcherTimer”和“常规计时器”)对UI的影响有何不同?

(直到阅读这篇文章我想过DispatcherTimer如使用WPF计时器的自然方式。什么情况下,当这是不是真的?)

回答

39

DispatcherTimer是普通计时器。它在UI线程上触发它的Tick事件,你可以用UI来做任何你想要的事情。 System.Timers.Timer是一个异步计时器,它的Elapsed事件在一个线程池线程上运行。你必须在你的事件处理程序非常小心,你都不准碰任何UI组件或数据绑定变量。而且,只要您访问在UI线程中使用的类成员,就需要使用锁语句。

在链接的答案,因为OP试图故意异步运行代码Timer类是比较合适的。

+0

注意,“接触”包括设置MVVM视图模型属性,以便使用DispatcherTimer你没事的时候,但有一个定时器,你甚至不能做到这一点 – 2012-09-15 04:19:44

26

Regular Timer的Tick事件实际上是在创建Timer的线程中触发的,所以在tick事件中,为了使用UI访问任何内容,必须通过dispatcher.begininvoke进行操作,如下所述。

RegularTimer_Tick(object sender, EventArgs e) 
{ 
    txtBox1.Text = "count" + i.ToString(); 
    // error can not access 
    // txtBox1.Text property outside dispatcher thread... 

    // instead you have to write... 
    Dispatcher.BeginInvoke((Action)delegate(){ 
     txtBox1.Text = "count " + i.ToString(); 
    }); 
} 

在调度定时器的情况下,您可以访问UI元素而不做开始调用或调用如下...

DispatcherTimer_Tick(object sender, EventArgs e) 
{ 
    txtBox1.Text = "Count " + i.ToString(); 
    // no error here.. 
} 

DispatcherTimer只是提供了方便了定期计时器可以方便地访问UI对象。

+1

谢谢你的代码示例,+1 – rem 2010-02-16 08:37:05

+0

是调度员计时器使用Invoke或BeginInvoke? – 2016-04-12 09:23:36

+0

基于这里的来源,DispatcherTimer使用BeginInvoke的,原因是,调度队列优先基于调用机制。 http://referencesource.microsoft.com/#WindowsBase/Base/System/Windows/Threading/DispatcherTimer.cs,d2a05f6b09eee858 – 2016-04-12 10:50:43

14

使用.NET 4.5,如果您需要使用新的.NET 4.5 await功能,则还可以为您的计时器创建一个async委托。

 var timer = new DispatcherTimer(); 
     timer.Interval = TimeSpan.FromSeconds(20); 
     timer.Tick += new EventHandler(async (object s, EventArgs a) => 
     { 
      Message = "Updating..."; 
      await UpdateSystemStatus(false); 
      Message = "Last updated " + DateTime.Now;    
     }); 
     timer.Start(); 
+0

这也可能是感兴趣的(我自己的问题寻求一个异步友好DispatcherTimer)http://stackoverflow.com /问题/ 12442622 /异步感知型-dispatchertimer - 包装 - 子/ 12442719#12442719 – 2012-09-15 21:32:41

相关问题