0

I have a program in which I want to pass multiple tasks to a BackGroundWorker in sequence. My problem is that the RunWorkerCompleted event is not being executed and the IsBusy flag is not being cleared. The ProgressChanged event does execute. The final statement in the DoWork routine does get executed. I can do the first task, but not any subsequent tasks.

Any ideas what to look at?

Edit (code added):

The notion (somewhat simplified) is like this:

for (int i = 0; i < cnt; i++)
            {
                string sDiv = dlg.GetItem(i).Substring(0, 5);
                bgw8Div.RunWorkerAsync(sDiv);
                // some kind of wait or delay or test needed here
            }

If cnt==1, all is well. If cnt>1, the RunWorkerCompleted event is never executed for case i==0 regardless of the wait or delay that I put in the loop.

SeaDrive
  • 4,182
  • 5
  • 32
  • 30
  • 3
    Please show your code. Any single BackgroundWorker is only meant to complete once. If you're waiting for extra tasks, you haven't really completed. – Jon Skeet May 19 '11 at 16:53
  • I moved the loop inside the BackgroundWorker, and it all executes OK, but now it's more complex to put the user messages that I want on the form to keep the user apprised of progress. – SeaDrive May 19 '11 at 18:14

1 Answers1

1

You have to create BackgroundWorker programmatically:

for (int i = 0; i < cnt; i++)
        {
            string sDiv = dlg.GetItem(i).Substring(0, 5);
            var bgw = new BackGroundWorker();
            // some kind of wait or delay or test needed here
            bgw.DoWork += 
            new DoWorkEventHandler(bw_DoWork);
            bgw.ProgressChanged += 
            new ProgressChangedEventHandler(bw_ProgressChanged);
            bgw.RunWorkerCompleted += 
            new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            bgw.RunWorkerAsync(sDiv);
        }  

Another option is to wait until your bgw8Div is completed. You can find more info at How to wait for a BackgroundWorker to cancel?. Of course, you'll lose the multi-threading features this way.

Community
  • 1
  • 1
Kamyar
  • 18,639
  • 9
  • 97
  • 171