In the process of developing winfrom with C. Progress bars are often used to display progress information. At this time, we may need to use multiple threads. If we do not use multiple threads to control the progress bar, the window will easily be suspended (the progress information cannot be seen in due time ). Next I will give you an introduction based on an example I wrote. Step 1: do not mention the design interface... note that you need to reference using system. Threading; Step 2: Define a proxy to update the value of progressbar)
- // Update Progress list
- PrivateDelegateVoidSetpos (IntIPOs );
Step 3: update the progress bar value function (the parameter must be the same as the declared proxy parameter)
-
- PrivateVoidSettextmessage (IntIPOs)
- {
-
- If(This. Invokerequired)
-
- {
-
- Setpos =NewSetpos (settextmessage );
-
- This. Invoke (setpos,NewObject[] {IPOs });
- }
-
- Else
-
- {
-
- This. Label1.text = IPOs. tostring () +/100";
-
- This. Progressbar1.value = convert. toint32 (IPOs );
-
- }
- }
Step 4: function implementation
- PrivateVoidButton#click (ObjectSender, eventargs E)
- {
- Thread fthread =NewThread (NewThreadstart (sleept ));// Open up a new thread
- Fthread. Start ();
- }
Step 5: The New thread executes the function:
- PrivateVoidSleept ()
-
- {
-
- For(IntI = 0; I <500; I ++)
-
- {
-
- System. Threading. thread. Sleep (100 );// There is no meaning, simple execution latency
-
- Settextmessage (100 * I/500 );
- }
-
- }
|
==================================
Use floating progress bar
1. Floating window
/// <Summary>
/// Increase process bar
/// </Summary>
/// <Param name = "nvalue"> the value increased </param>
/// <Returns> </returns>
Public bool increase (INT nvalue)
{
If (nvalue> 0)
{< br> If (prcbar. value + nvalue {< br> prcbar. value + = nvalue;
return true;
}
Else
{
Prcbar. value = prcbar. maximum;
This. Close ();
Return false;
}
}
Return false;
}
2. Progress window
Using system. Threading;
Private frmprocpolicar myprocessbar = NULL;
Private delegate bool increasehandle (INT nvalue );
Private increasehandle myincrease = NULL;
Private void showprocessbar ()
{
Myprocessbar = new frmprocessbar ();
// Init increase event
Myincrease = new increasehandle (myprocessbar. increase );
Myprocessbar. startposition = formstartposition. centerscreen;
Myprocessbar. showdialog ();
Myprocessbar = NULL;
}
Private void threadfun ()
{
Methodinvoker MI = new methodinvoker (showprocessbar );
This. begininvoke (MI );
Thread. Sleep (1000); // sleep a while to show window
Bool blnincreased = false;
Object objreturn = NULL;
Do
{
Thread. Sleep (50 );
Objreturn = This. Invoke (this. myincrease, new object [] {2 });
Blnincreased = (bool) objreturn;
}
While (blnincreased );
}
Usage:
Thread thdsub = new thread (New threadstart (threadfun ));
Thdsub. Start ();