BackgroundWorker and foreach loop
- by tomfox66
I have to process a loop with backgroundworkers.
Before I start a new loop iteration I need to wait until the provious backgroundworker has finished.
A while loop inside my foreach loop with isbusy flag doesn's seem like a good idea to me.
How should I design this loop so it waits for the bg-worker to end before iterating 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!";
}
}