Public Partial classForm1:form { PublicForm1 () {InitializeComponent (); //method One: Do not cross-thread security checks//System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false; } Private voidButton1_Click (Objectsender, EventArgs e) {Thread Th1=NewThread (NewThreadStart (calnum)); Th1. Start (); } Private voidCalnum () {//button1. Enabled = false; intresult =0; for(inti =1; I <100000000; i++) {result+=i; } setcalresult (Result); //button1. Enabled = true; } //Method Two: Check whether to cross the thread, then add the method to the delegate, call the delegate Public Delegate voidSettexthandler (intresult); Private voidSetcalresult (intresult) { if(Label2. invokerequired)//Waiting for asynchronous{SettexthandlerSet=NewSettexthandler (Setcalresult);//the method parameters of the delegate should be consistent with SetcalresultLabel2. Invoke (Set,New Object[] {result});//the second parameter of this method is used to pass in the method instead of the formal parameter result } Else{Label2. Text=result. ToString (); } } }
C # A workaround for cross-thread access controls