Differences between timer and dispatchertimer classes in WPF

Source: Internet
Author: User

In the morning, when I blew water in a WPF group, someone suddenly asked a question. He wanted to use a timer Timer class to update the control content on the interface in real time, but always encountered an exception: system. invalidoperationexception {"The Calling thread cannot access this object because another thread owns this object. "}.

So I dragged two label controls and tested them on WPF,CodeAs follows:

 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 /// <Summary>
19 /// Interaction logic for mainwindow. XAML
20 /// </Summary>
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 }

During debugging, this exception was thrown when timelabel. content was assigned a value in row 38th.

Google searched and found: "accessing Windows Forms controls is not thread-safe in nature. If two or more threads operate on the status of a control, the control may be forced to enter an inconsistent state. Other thread-related bugs may also occur, including contention and deadlocks. It is important to ensure that controls are accessed in a thread-safe manner. "-- From msdn http://msdn.microsoft.com/zh-cn/library/ms171728 (En-US, vs.80). aspx

Ah, the group replied: the sub-thread cannot access the interface thread objects. I have never learned C # (indeed, I learned C # to read a hundred pages in a week). This sentence is indeed not rigorous, because there are methods, it can be accessed through delegation. At the same time, the interface thread objects refer to controls, such as labels and textbox. Previously, I wrote a QTProgramThis is also the case when a similar problem occurs: In the child thread, an attempt is made to directly update an image on the interface. As a result, the program crashes and debugging takes a long time to discover the problem.

Now I think of an exercise I have done a while ago. I use dispatchertimer to update it. I tested it and found it feasible !!

 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 /// <Summary>
20 /// Interaction logic for mainwindow. XAML
21 /// </Summary>
22 Public Partial Class Mainwindow: Window
23 {
24 Private 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 }

So curious, what is the difference between the two?

After carefully reading the documentation on msdn, we can know that the implementation of dispatchertimer in the interface thread can be safely accessed and the interface content can be modified.

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 the dispatchertimer runs on the same thread as the dispatcher and a dispatcherpriority can be set on the dispatchertimer .

The difference is here !!
Note: thanks to the experts in the group for their guidance, timer is used, and invoke or begininvoke is used to update the UI (the advantage is that the wait action or long time is executed in dispatchertimer, the UI may be suspended ):

 1   Using System;
2 Using System. windows;
3 Using System. Timers;
4 Using System. Windows. Threading;
5
6 Namespace Timertest
7 {
8 /// <Summary>
9 /// Interaction logic for mainwindow. XAML
10 /// </Summary>
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 }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.