How a sub-thread calls a UI thread

Source: Internet
Author: User

In vs2005, subthreads are not allowed to use controls in the UI. The solutions on the Internet include: using controls for invoke. However, in my own applications, it is always troublesome: I want to call the processing in a main thread from the Child thread. I need to use a delegate, while the invoke still needs to use the delegate to bypass and confuse people. I slightly changed the structure to make it easier to call the handler in the UI thread in the Child thread.

In the Thread class, define

Public Delegate void receivedhandlerui (Object OBJ); // receives and processes the request, involving the UI

Use two variables. The second one is any control on the interface, which is mainly used to return to the UI thread.

Public receivedhandlerui onreceivedui; // receives processing functions, involving the UI
Public System. Windows. Forms. Control uictrol; // any control in the interface

Association Method

Public void setreceiveduserui (receivedhandlerui RH, system. Windows. Forms. Control CTL)
{
Onreceivedui = RH;
Uictrol = CTL;
}

The sub-thread must call the processing in the UI:

If (onreceivedui! = NULL & uictrol! = NULL)
{
Uictrol. Invoke (onreceivedui, State );
}

 

---------------------------------------------

Processing in the UI often changes, but as long as this is done

Threadobj. setreceiveduserui (New receivedhandlerui (myreceivedhandlerui), this );

// Interface processing
Void myreceivedhandlerui (Object OBJ)
{
Lineinfo li = (lineinfo) OBJ;
Textbox2.text + = "received data:" + Li. retrievefrombuffer () + "\ r \ n ";
}

 

MyProgramThe processing of sub-threads is relatively stable, but the processing on the main interface is relatively changing. In this way, you can quickly write the required processing program and use any control. At the same time, because it is executed in the UI thread, you do not need to consider concurrency thread security when operating the control.

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.