Use the backgroundworker component in. NET 2.0 applications to implement a progress bar

Source: Internet
Author: User
Author: Michael livshitz Translator: lilyonwin...

Author Michael livshitz July 3, 2007

Backgroundworker allows the form to complete an operation asynchronously. This function is useful when we need to perform operations such as "database transactions" or "image downloads. In this case, we can stop the response on the user interface (or hide it until the operation ends ). In this article, I will step by step teach you how to use the backgroundworker component in. NET 2.0 programs to process time-consuming operations. The sample program is written in C.

As usual, we create a test project named "testbgw" to contain only one form ("formbgw "):

Figure 1.

We will use backgroundworker to complete some database transaction operations (for example, getting some datatable data ). Drag a backgroundworker component to our form.

Figure 2.

We will use datatable to set the datasource attribute of datagridview1. We should also refresh our user interface and tell the user that all operations are "OK", so he/she doesn't have to worry about it any more. Therefore, we need a statusstrip and a timer.


Figure 3.

To let users see that our processing process is running, we will use toolstripprogressbar1:

Figure 4.

Toolstripstatuslabel1 and toolstripstatuslabeltime are used to display the status and time spent in the processing process to the user.

The form looks like this:


Figure 5.

To simulate database transaction operations, we will use getdata. dll (of course you can also connect to a real database; this simulation is only for testing ). For this purpose, we add getdata. DLL to the reference, and then write the getdatatable method:

Private datatable getdatatable (INT rows) {getdata. getdatahelp getdata = new getdata. getdatahelp (); Return (getdata. getdatasetcities (rows). Tables [0]);}
We call the runwokerasync method to start our Asynchronous Operation:
Private void formbgw_activated (Object sender, eventargs e) {backgroundworker1.runworkerasync ();}
The backgroundworker component has three events: Figure 6.
The dowork event occurs when the runwokerasync method is called. In the processing function of this event, we "complete" the time-consuming work (we load at least 100000 rows of data to make our processing process "time-consuming "), it notifies the user that the loading is in progress, and finally sets our able as the result of our asynchronous operation.
Private void backgroundworker=dowork (Object sender, doworkeventargs e) {datatable DT; toolstripstatuslabel1.text = "loading... & quot; + & quot; thanks for your patience & quot; dt = getdatatable (1000000); E. result = DT ;}
In terms of the situation we are facing (I mean the real situation, that is, the situation of obtaining some datatable data from the database ), there is no way to track the number of data rows (one row after one row) in the Insert Process ). Of course, we also have no way to know how many data rows can be obtained from the Database Based on our requests. Therefore, we will not use the reportprogress method of doworkeventargs to trigger the progresschanged event. We will use timer1 to show the user that the processing process is in progress (We will "add" toolstripprogressbar1 to the maximum level, and then start from the shortest length; that is to say, we will make some loops ). Therefore, we add the following code to timerjavastick:

If (toolstripprogressbar1.value = toolstripprogressbar1.maximum) {toolstripprogressbar1.value = 0 ;}
To let the user know how long it has taken to load, we have to add a bit of code to this method, for example:

String stime = "... "+ ts. minutes. tostring ("00") + ":" + ts. seconds. tostring ("00") + ":" + ts. milliseconds. tostring ("000"); toolstripstatuslabeltime. TEXT = stime;
TS indicates the current time (see the complete code below ).

By the way, if you only want to test how reportprogress works, you can add the following code to the backgroundworkerjavasdowork method:

// ------- To try percentage... int IMAX = 100000; For (INT I = 0; I <IMAX; I ++) {backgroundworker1.reportprogress (I * 100)/(IMAX-1 ));} then add the code to the backgroundworker1_progresschanged:

Privateprogresschangedeventargs e) void backgroundworkerprogress progresschanged (Object sender, {// ------- to try percentage... toolstripprogressbar1.value = E. progresspercentage; toolstripstatuslabel1.text = "loading... "+ E. progresspercentage. tostring () + "% ";//-------------------------}
The runworkercompleted event occurs when the background operation is complete. In this case, we will "close" all loading prompts and bind the datagridviewcites to the able by using the event parameter runworkercomletedeventargs:

Datagridviewcities. datasource = E. result;

The code for formbgw. CS is as follows:

Using system; using system. collections. generic; using system. componentmodel; using system. data; using system. drawing; using system. text; using system. windows. forms; namespace testbgw {public partial class formbgw: FORM {public formbgw () {initializecomponent (); // to try percentage... // backgroundworker1.workerreportsprogress = true;} # region "forclass" datetime startdate = datetime. now; # endregion private void formbgw_activated (Object sender, eventargs e) {response (); timer1.start ();} private void backgroundworker=dowork (Object sender, doworkeventargs e) {datatable DT; toolstripstatuslabel1.text = "loading... "+" thanks for your patience "; dt = getdatatable (1000000 );
/// ------- To try percentage... // int IMAX = 100000; // For (INT I = 0; I <IMAX; I ++) // {// backgroundworker1.reportprogress // (I * 100) /(IMAX-1 ));//}////-------------------------
E. result = DT; toolstripstatuslabel1.text = "please, wait... ";} private void backgroundworkerprogress progresschanged (Object sender, progresschangedeventargs e) {// ------- to try percentage... // toolstripprogressbar1.value = E. progresspercentage; // toolstripstatuslabel1.text = "loading... "+ // E. progresspercentage. tostring () + "%"; // response} private void backgroundworkerappsrunworkercompleted (Object sender, runworkercompletedeventargs e) {toolstripprogressbar1.value = 100; datagridviewcities. datasource = E. result; toolstripstatuslabel1.text = ""; toolstripprogressbar1.value = 0; timer1.stop (); toolstripstatuslabeltime. TEXT = "";} private datatable getdatatable (INT rows) {getdata. getdatahelp getdata = new getdata. getdatahelp (); Return (getdata. getdatasetcities (rows ). tables [0]);} private void timereffectick (Object sender, eventargs e) {timespan Ts = datetime. now. subtract (startdate); string stime = "... "+ ts. minutes. tostring ("00") + ":" + ts. seconds. tostring ("00") + ":" + ts. milliseconds. tostring ("000"); toolstripstatuslabeltime. TEXT = stime; If (toolstripprogressbar1.value = Break) {toolstripprogressbar1.value = 0;} toolstripprogressbar1.20.mstep () ;}} now, if we run our project, we will see Figure 7. after loading: Figure 8.ConclusionI hope this article will help you use the bakcgroundworker component in your. NET 2.0 program to perform some time-consuming operations.
Good luck with programming!
--------------

The translator's words are my first translation. From my perspective, I disagree with a programmer who cannot understand the original article. However, I don't like to give up because I have completed the translation task.

········································... Attached: I changed the previously called Method to the computation febonesi function. All the code is as follows:

Using system;
Using system. Collections. Generic;
Using system. componentmodel;
Using system. Data;
Using system. drawing;
Using system. text;
Using system. Windows. forms;

Namespace testbgw
{
Public partial class formbgw: Form
{
Datetime startdate = datetime. now;
Public formbgw ()
{
Initializecomponent ();
}

Private void backgroundworker=dowork (Object sender, doworkeventargs E)
{
Toolstripstatuslabel1.text = "loading..." + "thanks for your patience ";

E. Result = This. computefibonacci (40 );

Toolstripstatuslabel1.text = "please, wait ...";

 

}

Private void backgroundworker1_progresschanged (Object sender, progresschangedeventargs E)
{

}

Private void backgroundworkerappsrunworkercompleted (Object sender, runworkercompletedeventargs E)
{
Toolstripprogressbar1.value = 100;

Toolstripstatuslabel1.text = "";

Toolstripprogressbar1.value = 0;

Timer1.stop ();

Toolstripstatuslabeltime. Text = "";

}

Private void timereffectick (Object sender, eventargs E)
{
Timespan Ts = datetime. Now. Subtract (startdate );

String stime = "..." + ts. Minutes. tostring ("00") +

":" + Ts. Seconds. tostring ("00") +

":" + Ts. milliseconds. tostring ("000 ");

Toolstripstatuslabeltime. Text = stime;

If (toolstripprogressbar1.value = toolstripprogressbar1.maximum)
{
Toolstripprogressbar1.value = 0;
}
Toolstripprogressbar1.20.mstep ();

}

Private void formbgw_activated (Object sender, eventargs E)
{
Backgroundworker1.runworkerasync (); // start Asynchronous Operation

Timer1.start ();
}

Private long computefibonacci (int n)
{
// The parameter n must be> = 0 and <= 91.
// Fib (N), with N> 91, overflows a long.
If (n <0) | (n> 91 ))
{
Throw new argumentexception (
"Value must be> = 0 and <= 91", "n ");
}

Long result = 0;

If (n <2)
{
Result = 1;
}
Else
{
Result = computefibonacci (n-1) +
Computefibonacci (n-2 );
}
Return result;
}

}
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.