Use an anonymous function to set the Form Control attribute () in the background thread

Source: Internet
Author: User

From http://www.cnblogs.com/evlon/archive/2009/10/24/1589344.html

Developing winform using dotnetfx2.0ProgramIt is often necessary to use background threads to perform operations, and update and display the operation process data, result data, and other information to the window. Because the form thread and the worker thread are not a thread, we cannot directly set the properties of the control in the form in the work thread, but need to use control. invoke (delegate del ,...). In fact, you can use an anonymous function for simple calls.

According to the standard practice on msdn, if there is a function:

 

Void Writemessage ( String MSG)
{
This . Tbmsg. Text + = MSG;
}

 

To call a function in a working thread, you must declare a delegate first:

 

Public   Delegate   Void Writemessagehandle ( String );

 

Then, call the following in the thread function:

 

Public   Void Threadproc ( Object OBJ)
{
..
This . Invoke ( New Writemessagehandle ( This . Writemessag, New   Object [] { " Hello World " }));
..
}

 

In fact, for the following sentence: This. tbmsg. Text + = MSG; It's a big deal. In C #2.0, we can be very simple: // First declare the delegate used for 10 thousand.
Public   Delegate   Void Voiddelegate ();

Public   Void Threadproc ( Object OBJ)
{
// This is the message to be output.
String MSG =   " Hello World " ;
.
// Because it is in the work thread, we do not need to handle this. invokerequired, directly call
// Use the anonymous function directly, so that you can use the MSG local variable. Haha is simple.
This . Invoke ( New Voiddelegate ( Delegate ()
{
// This is the function to be executed.
This . Tbmsg. Text + = MSG;

// Other Code related to the form can also be called here
// Ex
// This. tbname. Text = "my name here ";
}));
.
}

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.