C# 比较 Timer 和 DispatcherTimer
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1111645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Comparing Timer with DispatcherTimer
提问by paradisontheitroad
what is a difference between System.Windows.Forms.Timer()
and System.Windows.Threading.DispatcherTimer()
? In which cases, we should use them? any best practices ?
是什么区别between System.Windows.Forms.Timer()
和System.Windows.Threading.DispatcherTimer()
?在哪些情况下,我们应该使用它们?任何最佳做法?
采纳答案by Reed Copsey
Windows.Forms.Timer
uses the windows forms message loop to process timer events. It should be used when writing timing events that are being used in Windows Forms applications, and you want the timer to fire on the main UI thread.
Windows.Forms.Timer
使用 windows 窗体消息循环来处理计时器事件。在编写在 Windows 窗体应用程序中使用的计时事件时应该使用它,并且您希望计时器在主 UI 线程上触发。
DispatcherTimer
is the WPF timing mechanism. It should be used when you want to handle timing in a similar manner (although this isn't limited to a single thread - each thread has its own dispatcher) and you're using WPF. It fires the event on the same thread as the Dispatcher.
DispatcherTimer
是 WPF 计时机制。当您想以类似的方式处理计时(尽管这不限于单个线程 - 每个线程都有自己的调度程序)并且您正在使用 WPF 时,应该使用它。它在与 Dispatcher 相同的线程上触发事件。
In general, WPF == DispatcherTimer
and Windows Forms == Forms.Timer
.
一般来说,WPF == DispatcherTimer
和Windows Forms == Forms.Timer
。
That being said, there is also System.Threading.Timer
, which is a timer class
that fires on a separate thread. This is good for purely numerical timing, where you're not trying to update the UI, etc.
话虽如此,还有System.Threading.Timer
,它是一个class
在单独线程上触发的计时器。这对于纯粹的数字计时很有用,您不会尝试更新 UI 等。
回答by Seekeer
I've found good article about timers with small examples here: http://www.progware.org/Blog/post/Timers-in-WPF.aspx
我在这里找到了关于计时器的好文章和小例子:http: //www.progware.org/Blog/post/Timers-in-WPF.aspx
As a conclusion:
作为结论:
If DoSomething() manipulates GUI components then with the Timer you need to use: this.Dispatcher.Invoke((Action)delegate { //GUI RELATED CODE HERE} since you cannot access GUI controls from a different thread directly. With DispatcherTimer you do not need to do that.
If DoSomething() performas a time-consuming task, then the GUI will freeze in the case of the DispatcherTimer. In the case of the Timer it won't since the long methos is executed in a different thread
如果 DoSomething() 操作 GUI 组件,那么你需要使用 Timer: this.Dispatcher.Invoke((Action)delegate { //GUI RELATED CODE HERE} 因为你不能直接从不同的线程访问 GUI 控件。使用 DispatcherTimer 你可以不需要这样做。
如果 DoSomething() 执行耗时的任务,那么在 DispatcherTimer 的情况下 GUI 将冻结。在 Timer 的情况下,它不会,因为长方法是在不同的线程中执行的