Invoke () performs the specified delegate on the main thread of the application. General application: This is called when the properties of an object in the UI thread (main thread) are modified in a worker thread. Invoke ();
//Test the form Public classTestform:form {//Create a Button object PrivateButton Button =NewButton (); //constructor Function PublicTestform () {//set the properties of a buttonbutton. Size =NewSize ( Max, -);//sizebutton. Click + = button1_clicked;//Registering Eventsbutton. Text ="Click Start Test";//Set display text This. Controls.Add (button);//Add to form This. Text ="Multithreaded Example";//set the title bar text for a form } //Button's Click event Response method Public voidButton1_clicked (Objectsender, EventArgs e) { //Start a thread NewThread (ThreadProc). Start (); } //Thread Functions Public voidThreadProc () {//This . Invoke is a way to access the UI across threads, and this is an example of this article//first invoke an anonymous delegate to disable the button object This. Invoke ((EventHandler)Delegate{button. Enabled=false; }); //record a timestamp to demonstrate the countdown effect intTick =Environment.tickcount; while(Environment.tickcount-tick < +) { //A cross-thread call updates the properties of a control on a form, where the Text property of the button object is updated This. Invoke ((EventHandler)Delegate{button. Text= ( +-Environment.tickcount + tick). ToString () +"start updating after microseconds"; }); //do a delay, avoid too fast, visual effect is not good. Thread.Sleep ( -); } //demo, 10 digit increment display for(inti =0; I <Ten; i++) { This. Invoke ((EventHandler)Delegate{button. Text=i.tostring (); }); Thread.Sleep ( $); } //Although not within the loop, please do not forget that your call is still in the worker thread, so you still need to invoke it. //restores the state, sets the text of the button to the initial state, and the Set button is available. This. Invoke ((EventHandler)Delegate{button. Text="Click Start Test"; button. Enabled=true; }); } }
Reprint: C # This.invoke () role multithreaded Operation UI Understanding two