C # threads access to controls

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.