The control class provides an Invoke method to give a child thread access to the main thread's controls, and its prototype is Jiangzi:
Object . Control.Invoke (Delegate method); Object. Control.Invoke (Delegate method,paramsobject[] args);
Method is a delegate object that has already been created, and if the object's associated methods have parameters, it is placed in the array args, without having to pass
The invoke consumption method is as follows (suppose I access the control by Getforms ()):
Public Delegate void getformsdelegate (parameter declaration of getforms); // declares a delegate type that matches the invocation of the method used to access the control, and the parameters must be consistent Public void MyThread () { // thread getformsdelegate () indirectly executes the method of accessing the control Getforms ( ) Invoke (new Getformsdelegate (getforms),newobject[] {getforms argument list});
Here's a complete example:
This is an example of having a thread output student information to a ListBox control
namespacethreadvisitingcontrol{ Public Partial classForm1:form { PublicForm1 () {InitializeComponent (); } Private voidShowstuifo (stringNostringNameDoubleScore)//The thread in this example accesses the control in the main thread through this method{LISTBOX1.ITEMS.ADD ("School Number:"+no); LISTBOX1.ITEMS.ADD ("Name:"+name); LISTBOX1.ITEMS.ADD ("Score:"+score. ToString ()); } Public Delegate voidStuinfodelegate (stringNostringNameDoubleScore);//declaring delegate types Private voidStuthread ()//Threading Methods{Invoke (NewStuinfodelegate (SHOWSTUIFO),New Object[] {"20101001","Zhang San",95.5});//The thread executes Showstuifo () through the delegate of the method, implementing access to the ListBox control } Private voidButton1_Click (Objectsender, EventArgs e) {Thread Stuth=NewThread (NewThreadStart (Stuthread));//Creating ThreadsStuth. Start ();//Execution Thread } }}
C # threads access to controls