早上在某WPF群里吹水,突然有人问了一个问题,他想利用一个计时器Timer类,实时更新界面上的控件内容,但是一直遇到抛出异常:System.InvalidOperationException {"调用线程无法访问此对象,因为另一个线程拥有该对象。"} 。
于是我就拖了两个Label控件,在WPF上测试起来,代码如下:
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Windows;
6 using System.Windows.Controls;
7 using System.Windows.Data;
8 using System.Windows.Documents;
9 using System.Windows.Input;
10 using System.Windows.Media;
11 using System.Windows.Media.Imaging;
12 using System.Windows.Navigation;
13 using System.Windows.Shapes;
14 using System.Timers;
15 16 namespace TimerTest
17 {
18 ///
19 /// Interaction logic for MainWindow.xaml
20 ///
21 public partial class MainWindow : Window
22 {
23 private Timer aTimer =
null;
24 public MainWindow()
25 {
26 InitializeComponent();
27 28 aTimer =
new Timer();
29 aTimer.Elapsed +=
new ElapsedEventHandler(OnTimedEvent);
30 // Set the Interval to 5 seconds.
31 aTimer.Interval =
1000;
32 aTimer.Enabled =
true;
33 aTimer.Start();
34 }
35 36 private void OnTimedEvent(
object source, ElapsedEventArgs e)
37 {
38 timeLabel.Content = DateTime.Now.ToUniversalTime();
39 }
40 }
41 }
Debug的时候,发现在第38行的时候,timeLabel.Content 赋值的时候抛出了该异常
Google搜索了一下发现:”访问 Windows 窗体控件本质上不是线程安全的。如果有两个或多个线程操作某一控件的状态,则可能会迫使该控件进入一种不一致的状态。还可能出现其他与线程相关的 bug,包括争用情况和死锁。确保以线程安全方式访问控件非常重要。“——来自MSDN
哎,在群上回答说了一句:子线程无法访问界面线程的对象。被指没学过C#(的确,我学C#就是在一周之内看完一本几百页的书),这句话说的的确不够严谨,因为是有方法的,可以通过委托的方式进行访问,同时,这个界面线程的对象是指控件,如Label,TextBox之类。之前都写一个Qt程序的时候也遇到类似的问题,也是类似的情况:在子线程中试图直接更新界面上的一张图片,结果程序奔溃了,调试了很久才发现问题所在。
这时候我就想起来前阵子做过的一个练习,使用DispatcherTimer来实现更新。测试了一下,发现可行啊!!
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Windows;
6 using System.Windows.Controls;
7 using System.Windows.Data;
8 using System.Windows.Documents;
9 using System.Windows.Input;
10 using System.Windows.Media;
11 using System.Windows.Media.Imaging;
12 using System.Windows.Navigation;
13 using System.Windows.Shapes;
14 using System.Timers;
15 using System.Windows.Threading;
16 17 namespace TimerTest
18 {
19 ///
20 /// Interaction logic for MainWindow.xaml
21 ///
22 public partial class MainWindow : Window
23 {
24 private DispatcherTimer dispatcherTimer =
null;
25 public MainWindow()
26 {
27 InitializeComponent();
28 29 dispatcherTimer =
new System.Windows.Threading.DispatcherTimer();
30 dispatcherTimer.Tick +=
new EventHandler(OnTimedEvent);
31 dispatcherTimer.Interval =
new TimeSpan(
0,
0,
1);
32 dispatcherTimer.Start();
33 }
34 35 private void OnTimedEvent(
object sender, EventArgs e)
36 {
37 timeLabel.Content = DateTime.Now.ToUniversalTime();
38 }
39 }
40 }
于是好奇这两者有什么不同?
仔细阅读MSDN上的文档后,可以得知:DispatcherTimer在界面线程中实现的,当然可以安全地访问,修改界面内容。
If a is used in a WPF application, it is worth noting that the 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 of the user interface (UI) thread using or . Reasons for using a DispatcherTimer opposed to a are that theDispatcherTimer runs on the same thread as the and a can be set on the DispatcherTimer.
呵呵,区别就是在这里了!!
附:感谢群里高手的指点,采用Timer,使用Invoke或者BeginInvoke的方式进行UI的更新的方式(好处在于:在DispatcherTimer里面执行等待动作或者时间过长,可能会导致UI假死):
1 using System;
2 using System.Windows;
3 using System.Timers;
4 using System.Windows.Threading;
5
6 namespace TimerTest
7 {
8 ///
9 /// Interaction logic for MainWindow.xaml
10 ///
11 public partial class MainWindow : Window
12 {
13 private Timer aTimer = null;
14
15 private delegate void TimerDispatcherDelegate();
16
17 public MainWindow()
18 {
19 InitializeComponent();
20
21 aTimer = new Timer(1000);
22 aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
23 aTimer.Interval = 1000;
24 aTimer.Enabled = true;
25 }
26
27 private void OnTimedEvent(object sender, EventArgs e)
28 {
29 this.Dispatcher.Invoke(DispatcherPriority.Normal,
30 new TimerDispatcherDelegate(updateUI));
31 }
32
33 private void updateUI()
34 {
35 timeLabel.Content = DateTime.Now.ToUniversalTime();
36 }
37 }
38 }