WPF multi-thread access control

Source: Internet
Author: User

We all know that the UI thread data cannot be directly accessed or modified by other threads when multiple threads access the UI control in WPF. How can this problem be solved?

There are two scenarios:

1. WinForm Program

1 2 1) first method, use delegate: 3 private delegate void SetTextCallback (string text); 4 private void SetText (string text) 5 {6 // InvokeRequired needs to compare the call thread ID and creation thread ID 7 // if they are different, true 8 if (this.txt _ Name. invokeRequired) 9 {10 SetTextCallback d = new SetTextCallback (SetText); 11 this. invoke (d, new object [] {text}); 12} 13 else14 {15 this.txt _ Name. text = text; 16} 17} 18 2) use anonymous delegate 19 private void SetText (Object Obj) 20 {21 if (this. invokeRequired) 22 {23 this. invoke (new MethodInvoker (delegate24 {25 this.txt _ Name. text = obj; 26}); 27} 28 else29 {30 this.txt _ Name. text = obj; 31} 32} 33 the difference between BeginInvoke and Invoke is described here: BeginInvoke will return immediately, and Invoke will return after execution.View Code

2. WPF Program

1) You can use the Dispatcher thread model to modify

For the form itself, you can use code similar to the following:

This. lblState. Dispatcher. Invoke (new Action (delegate {this. lblState. Content = "state:" + this. _ statusText ;}));

What if a window or playing sound is displayed in a public class? Here we can use: System. Windows. Application. Current. Dispatcher, as shown below:

 System.Windows.Application.Current.Dispatcher.Invoke(new Action(() => {     if (path.EndsWith(".mp3") || path.EndsWith(".wma") || path.EndsWith(".wav"))     {        _player.Open(new Uri(path));        _player.Play();    } }));

 

 

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.