Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BackgroundWorker ReportProgress no loop just long database operation

I have .NET 4.5 Windows Forms application where one of the methods takes a while to complete (it's a BulkCopy function which loads a considerable amount of data and pushes into SQL).

I would like to use a BackgroundWorker and ReportProgress so the user will know that there is something going on. I made a few applications that use this but all of them are in some kind of a loop when the BackgroundWorker is doing work and I can easily ReportProgress inside each loop step.

Here I have a problem because there is no loop, code steps would be:

  1. worker start async
  2. get data from DB2 into a datatable (this takes the most time)
  3. SqlBulkCopy datatable into SQL table

I would need to start reporting progress (albeit a fake progress percentage, a simple spinning progress bar would suffice) between step 1. and 2. and end reporting progress after step 3.

Anyone had a similar problem/solution, I guess I could just display a GIF image and hide it after work is done, but I think this won't work as the form freezes (Not responding message).

like image 428
Iztoksson Avatar asked Feb 13 '23 05:02

Iztoksson


2 Answers

You can use the Marquee style of the ProgressBar to show indeterminate length of an active process:

BackgroundWorker bgw = new BackgroundWorker();
bgw.DoWork += bgw_DoWork;
bgw.RunWorkerCompleted += bgw_RunWorkerCompleted;
progressBar1.Style = ProgressBarStyle.Marquee;
progressBar1.MarqueeAnimationSpeed = 50;
bgw.RunWorkerAsync();

void bgw_DoWork(object sender, DoWorkEventArgs e) {
  // long work
}

void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
  progressBar1.Style = ProgressBarStyle.Continuous;
  progressBar1.MarqueeAnimationSpeed = 0;
}
like image 195
LarsTech Avatar answered Feb 16 '23 04:02

LarsTech


The simplest solution is to display an animated GIF image on the form. The form will not freeze the animation as long as the work is being done properly in a background thread. If the form is still freezing, that means it's not actually doing the work on the background thread like you think it is. Alternatively, you could use a timer to periodically update another kind of control such as a progress bar.

like image 44
Steven Doggart Avatar answered Feb 16 '23 03:02

Steven Doggart