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(); } }));