Avoid the begininvoke dance during thread Switching

Source: Internet
Author: User

What is the begininvoke dance.

Delegate void myhandlerdelegate ();
Void myhandler ()
{
// "The begininvoke dance"
If (this. invokerequired ){
Begininvoke (New myhandlerdelegate (myhandler ));
Return;
}
Do GUI stuff
}

When developing multi-threaded programs, we often need to feedback the results to the UI after a large amount of computing. if you update the UI directly when multithreading occurs, an exception is thrown. I believe everyone has encountered such a problem, and the solution is the above so-called begininvoke dance.

 

Asyncoperationmanager is provided in 2.0. classes that support asynchronous method calls provide concurrent management. It can be used to avoid begininvoke. Besides, it is annoying to write such a stuff every time.

Public partial class form1: Form
{
Asyncoperation;
Public form1 ()
{
Initializecomponent ();
}

Private void button#click (Object sender, eventargs E)
{
Asyncoperation = asyncoperationmanager. createoperation (null );
Thread t = new thread (New threadstart (runtask ));
T. Start ();
}

Public void runtask ()
{
Thread. Sleep (5000 );
Asyncoperation. Post (New sendorpostcallback (showtext), "hello ");
}

Void showtext (Object S)
{
This. textbox1.text = S. tostring ();
}
}

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.