Today, when I was working on a winform project, I encountered a problem that I needed to update the GUI across threads. By default, winform does not allow cross-thread update of GUI controls. If you do this, an error is reported, therefore, we need to make some changes. In my solution, we use the updating your form from another thread without creating delegates for every type of update.CodeThe Code is as follows:
// Create a class for adding extension methods
Public Static Class Extensionmethod
{
Public Static Tresult safeinvoke <t, tresult> ( This T ISI, func <t, tresult> call) Where T: isynchronizeinvoke
{
If (ISI. invokerequired ){
Iasyncresult result = Isi. begininvoke (call, New Object [] {ISI });
Object Endresult = Isi. endinvoke (result ); Return (Tresult) endresult;
}
Else
{
Return Call (ISI );
}
}
Public Static Void Safeinvoke <t> ( This T ISI, Action <t> call) Where T: isynchronizeinvoke
{
If (ISI. invokerequired)
{
Isi. begininvoke (call, New Object [] {ISI });
}
Else
{
Call (ISI );
}
}
}
// Such an application in a class
Private Void Button#click ( Object Sender, eventargs E)
{
Thread thread = New Thread ( New Threadstart (startcalculation ));
Thread. Start ();
}
Private Void Startcalculation ()
{
Button1.safeinvoke (D => D. Enabled = False );
For ( Double I = 0 ; I <= 10000000000 ; I ++)
{
String Textforlabel = (I) + " % " ;
Lblprocent. safeinvoke (D => D. Text = textforlabel );
VaR I1 = I;
Progressbar1.safeinvoke (D => D. value = 10 );
String Labeltext = lblprocent. safeinvoke (D => D. Text );
}
This . Safeinvoke (D => D. refreshtree ());
Button1.safeinvoke (D => D. Enabled = True );
}
Private Void Refreshtree ()
{
Thread. Sleep ( 10000 );
This . Treeview1.expandall ();
This . Treeview1.nodes [ 0 ]. Nodes [ 1 ]. Remove ();
}
note that the startcalculation method is executed in the new thread, but safeinvoke (for example, refreshtree ) it is still executed in the main thread . If you have resource-consuming code in these methods (such as the thread here. sleep ( 10000 )) the Program still has a false dead state of stopping the response.