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