In C # WinForm programs, using threads to update the interface requires special handling, otherwise the exception "Between threads is invalid: it is accessed from a thread that is not creating the control" Taskview ". ”
In the net text "http://www.cnblogs.com/smileberry/p/3912918.html" know, I did the following routine, I hope to help you, if the comments are not enough, please visit the original text.
The routine is to click the button after the start thread updates a label text, the interface is as follows:
The procedure is as follows:
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Windows.Forms;usingSystem.Threading;namespacethreadcggui{ Public Partial classForm1:form {//Defining delegate Types Delegate voidsettextcallback (String str); PublicForm1 () {InitializeComponent (); } //Click the button to start the thread Private voidButton1_Click (Objectsender, EventArgs e) {Thread th=NewThread (Threadprocsafe); Th. Start (); } //Thread Principal method Private voidThreadprocsafe () { for(inti =0; I < +; i++) { ifI2==0) { This. SetText ("123456789"); } Else { This. SetText ("123456789"); } thread.sleep ( +); } } //This method is a popular method of updating the UI across threads, using the Invoke/begininvoke method of the control to move the delegate to the UI thread called to implement thread-safe updates//In essence, the message that is being committed in the thread is passed to the UI thread through the control handle call delegate. Public voidSetText (String str) {if(Label1. invokerequired) {//resolve a "access disposed handle" exception when the form is closed while(Label1. ishandlecreated = =false) { if(Label1. Disposing | | Label1. isdisposed)return; } settextcallback D=NewSettextcallback (SetText); Label1. Invoke (d,New Object[] {str}); } Else{Label1. Text=str; } } Private voidForm1_formclosed (Objectsender, Formclosedeventargs e) { //a complete exitSystem.Environment.Exit (0); } }}
Routine Download:
Http://files.cnblogs.com/files/xiandedanteng/ThreadCgGui20170626.zip
C # Error "Invalid inter-thread operation: access it from a thread that is not creating a control" XXX "--Solving the example