WINFORMWPF multithreaded access control "Go"

Source: Internet
Author: User
Tags access properties

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"

Related Article

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.