BackgroundWorker and foreach loop

I need to handle the loop using background wizards.

Before I start a new iteration of the loop, I need to wait until the experienced background worker is finished.

The while loop inside my foreach loop with the isbusy flag doesn't seem like a good idea to me.

How do I create this loop so that it waits for bg-worker to complete before repeating the loop

public void AutoConnect()
{
    string[] HardwareList = new string[] { "d1", "d4", "ds1_2", "ds4_2" };
    foreach (string HW in HardwareList)
    {
        if (backgroundWorker1.IsBusy != true)
        {
            backgroundWorker1.RunWorkerAsync(HW);
            // Wait here until backgroundWorker1 finished
        }
    }
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{

    BackgroundWorker worker = sender as BackgroundWorker;
    string FileName = e.Argument as string;
    try
    {
        if ((worker.CancellationPending == true))
        {
            e.Cancel = true;
        }
        else
        {
            // Time consuming operation
            ParseFile(Filename);
        }
    }
    catch { }
}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    label1.Text = e.ProgressPercentage.ToString() + " lines";
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if(e.Cancelled == true)
    {
        //this.tbProgress.Text = "Canceled!";
    }
    else if(!(e.Error == null))
    {
        //this.tbProgress.Text = ("Error: " + e.Error.Message);
    }
    else
    {
        label1.text = "Done!";
    }
}

      

+2


a source to share


2 answers


You are using your flashlight incorrectly. Pass the entire list to the background worker and run the foreach loop.



public void AutoConnect()
{
    string[] HardwareList = new string[] { "d1", "d4", "ds1_2", "ds4_2" };
    backgroundWorker1.RunWorkerAsync(HardwareList);
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{

    BackgroundWorker worker = sender as BackgroundWorker;
    string[] FileNames = e.Argument as string[];
    int i = 0;

    foreach (string FileName in FileNames)
    {
       ParseFile(FileName);
       worker.ReportProgress(++i);
       if (worker.CancellationPending)
       {
          e.Cancel = true;
          break;
       }
    }
}

      

+12


a source


The main idea is to move foreach to DoWork method. This can use undo (doesn't seem very efficient now).



string[] HardwareList = new string[] { "d1", "d4", "ds1_2", "ds4_2" };
backgroundWorker1.RunWorkerAsync(HardwareList);


private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;
    string[] HardwareList = e.Argument as string[];

    foreach (string HW in HardwareList)
    {
        if (worker.CancellationPending) ...
        .... 
    }
}

      

+4


a source







All Articles