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.