DispatcherTimer 与 WPF 应用程序中用于任务调度程序的常规计时器 [英] DispatcherTimer vs a regular Timer in WPF app for a task scheduler

查看:21
本文介绍了DispatcherTimer 与 WPF 应用程序中用于任务调度程序的常规计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请解释@Kent Boogaart 在多线程 WPF 应用程序中用作本主题中的任务调度程序的DispatcherTimer"和常规计时器"之间的区别:

Please, explain the difference between "DispatcherTimer" and "a regular Timer" that @Kent Boogaart meant for using in a multithreading WPF app as a task sheduler in this topic:

WPF 应用程序的多线程策略所需的建议

在其中一篇文章的评论中(引用):

in the commentaries to one of the post (quote):

-如果 DispatcherTimer 所做的只是启动另一个线程,那么使用 DispatcherTimer 的意义何在?....那些线程不需要在 UI 线程上启动.您可以只使用常规计时器并避免完全中断 UI

常规计时器"是什么意思?它们(DispatcherTimer"和常规计时器")对 UI 的影响有何不同?

(在阅读这篇文章之前,我认为 DispatcherTimer 是在 WPF 中使用计时器的一种自然方式.如果情况并非如此?)

(Until reading this post I thought about DispatcherTimer as a natural way of using timers in WPF. What is the cases when this is not true?)

推荐答案

DispatcherTimer 是常规计时器.它在 UI 线程上触发它的 Tick 事件,你可以对 UI 做任何你想做的事情.System.Timers.Timer 是一个异步定时器,它的 Elapsed 事件在线程池线程上运行.在事件处理程序中必须非常小心,不允许触摸任何 UI 组件或数据绑定变量.并且您需要在访问类成员时使用 lock 语句,这些成员也在 UI 线程中使用.

DispatcherTimer is the regular timer. It fires its Tick event on the UI thread, you can do anything you want with the UI. System.Timers.Timer is an asynchronous timer, its Elapsed event runs on a thread pool thread. You have to be very careful in your event handler, you are not allowed to touch any UI component or data-bound variables. And you'll need to use the lock statement where ever you access class members that are also used on the UI thread.

在链接的答案中,Timer 类更合适,因为 OP 试图故意异步运行代码.

In the linked answer, the Timer class was more appropriate because the OP was trying to run code asynchronously on purpose.

这篇关于DispatcherTimer 与 WPF 应用程序中用于任务调度程序的常规计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆