WinForm UI controls for inter-process operations

Source: Internet
Author: User

One, the problem description.

When a new thread is created outside of the main thread, we want to modify the properties of the main interface control by creating new threads, and Windows will make an error indicating that the inter-process action UI is invalid.

Two, the solution.

1, not a good practice, there is a certain role, not recommended.

 Public Form1 () {                   false;//This setting is equivalent to letting vs agree to such interprocess action}

2, use the delegate to operate. The equivalent of a third party appears between the new process and the main process, which passes the requirements of the new process to the main process and then the main process executes.

//Non-parametric method
Private voidButton1_Click (Objectsender, EventArgs e)//button event in new Thread {ThreadStart ThreadStart=NewThreadStart (dosomething); Thread Mythread=NewThread (ThreadStart); Mythread. Start (); } Delegate voidMyDelegate (); Delegate Method Public voidWhat to do in dosomething ()//new Thread {if( This. invokerequired) { This. Invoke (Newmydelegate (dosome)); } Else { } } Public voiddosome ()//the method that actually operates the UI, executed by the delegate {button1. Text="Hellow C #"; }

3, consider the method with the parameter condition

Private voidButton1_Click (Objectsender, EventArgs e) {Thread Mythread=NewThread (NewParameterizedthreadstart (dosomething));//creates a new thread that associates the method that the thread will executeMythread. Start ("Hellow C #"); }        Delegate voidMyDelegate (stringstr);  Public voidDoSomething (Objectobj) {            if( This. invokerequired) { This. Invoke (NewMyDelegate (dosome), obj); }            Else            {                       }                  }           Public voidDosome (stringstr) {button1. Text=str; }    }

WinForm UI controls for inter-process operations

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.