1. The system. Windows. Forms. methodinvoker type is a system-defined delegate used to call methods without parameters.
Private thread mythread;
Private void form1_load (Object sender, eventargs E)
{
Mythread = new thread (New threadstart (runsonworkerthread ));
Mythread. Start ();
}
Private void runsonworkerthread ()
{
Methodinvoker MI = new methodinvoker (setcontrolsprop );
Begininvoke (MI );
}
Private void setcontrolsprop ()
{
Label1.text = "mythread thread calls UI control ";
}
2. directly use system. eventhandle (with parameters)
Private thread mythread;
Private void form1_load (Object sender, eventargs E)
{
Mythread = new thread (New threadstart (runsonworkerthread ));
Mythread. Start ();
}
Private void runsonworkerthread ()
{
// Dosomethingslow ();
String plist = "mythread thread calls UI control ";
Label1.begininvoke (new system. eventhandler (updateui), plist );
}
// Directly use system. eventhandler, and there is no need to customize the delegate
Private void updateui (Object o, system. eventargs E)
{
// Set the label1 attribute in the UI thread
Label1.text = O. tostring () + "successful! ";
}
Iii. Demo program
/// <Summary>
/// Provides the system with the purpose of entrusting event calls to solve the interface controls within the thread
/// </Summary>
/// <Param name = "OBJ"> </param>
/// <Param name = "E"> </param>
Private void updatelistbox (Object OBJ, system. eventargs E)
{
// Force type conversion
List <string> paramlist = (list <string>) OBJ;
If (paramlist [0] = "0 ")
{
This. lstboxcatchdata. Items. Clear ();
}
Else if (paramlist [0] = "1 ")
{
This. lstboxcatchdata. Items. Add (paramlist [1]. tostring ());
}
}
Call part in the thread:
// Initialize the parameter list
List <string> paramlist = new list <string> ();
Paramlist. Add ("0 ");
Paramlist. Add ("");
// The system delegate method is used to implement the interface controls of the operating system in the thread.
Paramlist [0] = "0"; paramlist [1] = "clear screen information ";
Lstboxcatchdata. begininvoke (new system. eventhandler (updatelistbox), paramlist );
End.