What do you know when multithreaded access to UI controls in WPF prompts the UI thread's data not to be accessed or modified directly by other threads?
In the following two cases
1.WinForm Program
1the first method, using a delegate:Private Delegate voidSettextcallback (stringtext); Private voidSetText (stringtext) { //invokerequired need to compare call thread ID and create thread ID//returns True if they are not the same if( This. txt_name.invokerequired) {Settextcallback D=NewSettextcallback (SetText); This. Invoke (D,New Object[] {text}); } Else { This. Txt_name.text =text; } }2the second method, using anonymous delegatesPrivate voidSetText (Object obj) {if( This. invokerequired) { This. Invoke (NewMethodInvoker (Delegate { This. Txt_name.text =obj; })); } Else { This. Txt_name.text =obj; }} Here is the BeginInvoke and invoke and the difference: BeginInvoke will return immediately, and invoke will wait until the execution is finished before returning.
WinForm can also directly set the settings to enable multi-threaded access properties, such as delegates and so on can not be added.
2.WPF Program
1) You can use the dispatcher threading model to modify
If the form itself can use code similar to the following:
this. LblState.Dispatcher.Invoke (thenew Action (delegate{ this" Status:"this. _statustext;} )";
So what if you pop a window, play a sound, etc 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 (thenew Uri (path)); _player. Play (); } }));
WINFORMWPF multithreaded access control "Go"