2
foreach (string file in listToConvert)
{
    BackgroundWorker backgroundWorker = new BackgroundWorker();
    backgroundWorker.WorkerReportsProgress = true;
    backgroundWorker.DoWork += new DoWorkEventHandler(
    (s3, e3) =>
    {
        newFile = sendFilesToConvert(file);
    });

    backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
    (s3, e3) =>
    {
        listBoxFiles.Items.Add(newFile);
    });

    backgroundWorker.RunWorkerAsync();
}

each file from the list will convert to another and i want that each BackgroundWorker will wait untill it's finish to convert and only then the next BackgroundWorker will start how can i do it ?

Random Dev
  • 51,810
  • 9
  • 92
  • 119
user979033
  • 5,430
  • 7
  • 32
  • 50

3 Answers3

2

Don't create a Bgw in each run of the loop. That's not a good idea anyway.

Just run the foreach() inside one single Bgw.

You can use the progress event to Add the results to the listbox or collect them in a list and Add them all at once when you're finished.

H H
  • 263,252
  • 30
  • 330
  • 514
1

You could use the TPL for this:

   Task<List<newFile>> task1 = Task<List<newFile>>.Factory.StartNew(() =>
   {
      List<newFile> newFiles = new List<newFile>();
     foreach(string file in fileList)
     {
        newFiles.Add(SendFilesToConvert(file));
     };

     return newFilesList;
   });


   foreach(newFile nFile in task1.Result)
   {
     listBoxFiles.Items.Add(nFile);
   };
Stephen Gilboy
  • 5,572
  • 2
  • 30
  • 36
0

As I understood, you want to update a UI element (listBoxFiles) in your scenario. So you can use the following code:

BackgroundWorker backgroundWorker = new BackgroundWorker();
backgroundWorker.WorkerReportsProgress = true;

var context = SynchronizationContext.Current;
var filesList = // clone your listToConvert if it's not a local variable or other threads can access it

backgroundWorker.DoWork += (s3, e3) =>
               {
                   foreach (string file in filesList)
                   {
                       var newFile = sendFilesToConvert(file);
                       context.Post(x => listBoxFiles.Items.Add(newFile), null);

                       // Report progress
                   }
               };

backgroundWorker.RunWorkerAsync();

this code posts a message (asynchronously) to your UI thread every time it needs to update your UI control, then UI thread dispatches it message and executes the code (ListBox.Items.Add(...)) in proper context.

oxilumin
  • 4,775
  • 2
  • 18
  • 25