I have a Background worker that needs to be called multiple times based on the number of checkboxes checked – I have written this to get the checkbox values and put them into a List.
List repSelected = new List();
This is populated and then iterated over like so:
foreach (string rep in repSelected)
{
backgroundWorker1.RunWorkerAsync(rep);
backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
}
The async, DoWork code looks like this:
BackgroundWorker worker = sender as BackgroundWorker;
string rep = e.Argument.ToString();
if (worker.CancellationPending == true)
{
e.Cancel = true;
}
else
{
DirectoryExists(rep);
ProcessRunner(rep); //Rars some large files - expensive
}
The process then runs WorkerComplete, the problem is when the process goes back to do the next iteration of the Worker it crashes out saying the worker is busy – even though the worker has returned it’s WorkerCompleted status.
How can I make sure that the thread is closed before the next iteration of the loop?
NB: I had a conditional on the background worker containing !backgroundWorker1.IsBusy() but this (obviously) just skipped over the remaining iterations without execution.
If you want to process each item in sequence, there is no reason to use a separate backgroundworker for each task. So it will be better to move the foreach loop into the DoWork method. But if you want to process all items in paralell, you need to create one background worker for each item.