To prevent interface deadlocks, It is troublesome to use thread control, and there will be a temporary interface deadlock. You can try to use backgroundworker.
Usage:
1) Add backgroundworker to the toolkit component to the interface;
2) modify the attributes workerreportsprogress and workersuppscanscancellation to true;
3) Click the dowork, runworkercompleted, and progresschanged events in the property event to generate the corresponding function.
4) Add the following controls on the interface:
Private system. componentmodel. backgroundworker backgroundworker1;
Private system. Windows. Forms. Label resultlabel;
Private system. Windows. Forms. progressbar progressbar1;
Private system. Windows. Forms. Button cancelasyncbutton;
Private system. Windows. Forms. Button startasyncbutton;
Private system. Windows. Forms. numericupdown numericupdown1;
Code:
Public partial class form2: Form
{
Public form2 ()
{
Initializecomponent ();
}
Private void backgroundworker=dowork (Object sender, doworkeventargs E)
{
Backgroundworker worker = (backgroundworker) sender;
E. Result = backgroundfunction (INT) E. argument, worker, e );
}
Private void backgroundworker1_progresschanged (Object sender, progresschangedeventargs E)
{
This. progressbar1.value = E. progresspercentage;
}
Private void backgroundworkerappsrunworkercompleted (Object sender, runworkercompletedeventargs E)
{
If (E. cancelled)
{
This. resultlabel. Text = "cancle ";
}
Else
{
If (E. Error! = NULL)
{
MessageBox. Show (E. Error. message ,"");
}
Else
{
This. resultlabel. Text = E. Result. tostring ();
}
}
}
Private void startasyncbutton_click (Object sender, eventargs E)
{
Int n = convert. toint32 (this. numericupdown1.value );
Backgroundworker1.runworkerasync (N );
}
Private void cancelasyncbutton_click (Object sender, eventargs E)
{
Backgroundworker1.cancelasync ();
}
Private int backgroundfunction (int n, backgroundworker worker, doworkeventargs E)
{
Int I = 0;
For (; I <n; I ++)
{
If (worker. cancellationpending)
{
E. Cancel = true;
Return I;
}
Worker. reportprogress (I * 100/N );
System. Threading. thread. Sleep (30 );
}
Return I;
}
}
}
Running result: the progress bar shows the running progress. You can cancel the operation.
Note:
InDoworkEvent ProcessingProgramCannot operate any user interface objects.InsteadProgresschangedAndRunworkercompletedThe event communicates with the user interface.
BackgroundworkerNo cross-EventAppdomainThe boundary for sending and receiving.Do not useBackgroundworkerComponents in multipleAppdomain.