Resolution of control manipulation problems for C # child threads

Source: Internet
Author: User

Control actions on C # child threads

In general, a control operation on a form directly on a child thread can cause an exception. This is because the child threads and the threads running the form are different spaces, so it is not possible to manipulate the controls on the form in a child thread simply by using the control object name, but rather than not being able to operate, Microsoft provides Invoke method, whose function is to let the child thread tell the form thread to complete the corresponding control operation.

Now with a thread-controlled process bar to illustrate, the approximate steps are as follows:

1. Create an invoke function, roughly as follows:

/// < summary>
/// Delegate function to be invoked by main thread
/// < /summary>
private void InvokeFun()
{
    if( prgBar.Value <  100 )
        prgBar.Value = prgBar.Value + 1;
}

2. C # Child thread entry function:

/// < summary>
/// Thread function interface  
/// < /summary>

private

void
 ThreadFun()
{
    //Create invoke method by specific function
    MethodInvoker mi =
new
 MethodInvoker(
this
.InvokeFun );

for
(
int
 i = 0; i <  100; i++ )
    {

this
.BeginInvoke( mi );
        Thread.Sleep( 100 );
    }
}

3. To create a C # child thread:

Thread thdProcess =
new
 Thread(
new
 ThreadStart( ThreadFun ) );
thdProcess.Start();

Note:

using
 System.Threading;

private
 System.Windows.Forms.ProgressBar prgBar;

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.