[.Net码农]WPF中Timer与DispatcherTimer类的区别
来源:互联网 发布:淘宝视频审核要多久 编辑:程序博客网 时间:2024/05/02 04:52
本文来自zhchbin的博客,原文地址:http://www.cnblogs.com/zhchbin/archive/2012/03/06/2381693.html
早上在某WPF群里吹水,突然有人问了一个问题,他想利用一个计时器Timer类,实时更新界面上的控件内容,但是一直遇到抛出异常:System.InvalidOperationException {"调用线程无法访问此对象,因为另一个线程拥有该对象。"} 。
于是我就拖了两个Label控件,在WPF上测试起来,代码如下:
Debug的时候,发现在第38行的时候,timeLabel.Content 赋值的时候抛出了该异常
Google搜索了一下发现:”访问 Windows 窗体控件本质上不是线程安全的。如果有两个或多个线程操作某一控件的状态,则可能会迫使该控件进入一种不一致的状态。还可能出现其他与线程相关的 bug,包括争用情况和死锁。确保以线程安全方式访问控件非常重要。“——来自MSDN http://msdn.microsoft.com/zh-cn/library/ms171728(en-us,VS.80).aspx
哎,在群上回答说了一句:子线程无法访问界面线程的对象。被指没学过C#(的确,我学C#就是在一周之内看完一本几百页的书),这句话说的的确不够严谨,因为是有方法的,可以通过委托的方式进行访问,同时,这个界面线程的对象是指控件,如Label,TextBox之类。之前都写一个Qt程序的时候也遇到类似的问题,也是类似的情况:在子线程中试图直接更新界面上的一张图片,结果程序奔溃了,调试了很久才发现问题所在。
这时候我就想起来前阵子做过的一个练习,使用DispatcherTimer来实现更新。测试了一下,发现可行啊!!
于是好奇这两者有什么不同?
仔细阅读MSDN上的文档后,可以得知:DispatcherTimer在界面线程中实现的,当然可以安全地访问,修改界面内容。
If a System.Timers.Timer is used in a WPF application, it is worth noting that the System.Timers.Timer runs on a different thread then the user interface (UI) thread. In order to access objects on the user interface (UI) thread, it is necessary to post the operation onto the Dispatcher of the user interface (UI) thread using Invoke or BeginInvoke. Reasons for using a DispatcherTimer opposed to a System.Timers.Timer are that theDispatcherTimer runs on the same thread as the Dispatcher and a DispatcherPriority can be set on the DispatcherTimer.
呵呵,区别就是在这里了!!
附:感谢群里高手的指点,采用Timer,使用Invoke或者BeginInvoke的方式进行UI的更新的方式(好处在于:在DispatcherTimer里面执行等待动作或者时间过长,可能会导致UI假死):
- [.Net码农]WPF中Timer与DispatcherTimer类的区别
- WPF中Timer与DispatcherTimer类的区别
- WPF中DispatcherTimer定时器的原理
- 实例对比WPF中的Timer和DispatcherTimer
- 实例对比WPF中的Timer和DispatcherTimer
- [.Net码农]WPF 下的Timer控件
- WPF下的DispatcherTimer研究
- WPF下的DispatcherTimer稳定性研究
- 通过制作一个简单的时钟学习WPF中DispatcherTimer的使用 Level 100
- [WPF] 初学WPF——DispatcherTimer简单的时钟
- WPF下DispatcherTimer问题
- WPF定时器-DispatcherTimer
- wpf中应该使用c#四种定时器中的DispatcherTimer
- wpf中应该使用c#四种定时器中的DispatcherTimer
- WPF中Auto与*的区别
- WPF中Auto与*的区别
- WPF中Auto与*的区别
- Timer(System.Timers) 和 DispatcherTimer
- android 调用javascript!
- 高层主管必须明白的七点
- Android 上SuperUser获取ROOT权限原理解析
- The launcher3 study notes for ICon change
- 那时的我还没剪去长发
- [.Net码农]WPF中Timer与DispatcherTimer类的区别
- Echarts 关于axisLabel中x抽值太长不自动换行的问题
- Redis安装部署
- Eclipse配置C#开发环境
- ajax的小例子
- ViewPager实现左右无限循环滑动
- ganglia 监控 windows
- jquery获取input值的各种情况
- 土豪的定义