Search code examples
c#backgroundworker

BackgroundWorker is currently busy and can not run multiple tasks concurrently


I am trying to iterate an array while using backgroundworker, I am sure it is just my syntax being incorrect, but I am constantly getting the error. Can someone assist me with what to do to rectify this?

namespace Form1
{
public partial class Form1 : Form
{
    public BackgroundWorker backgroundWorker1 = new BackgroundWorker();
    public OpenFileDialog fd = new OpenFileDialog();

    public Form1()
    {
        InitializeComponent();
        backgroundWorker1.WorkerReportsProgress = true;
        backgroundWorker1.WorkerSupportsCancellation = true;
        backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
        backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
    }
    private void btn_Two_Click(object sender, EventArgs e)
    {
        fd.Title = "Select The Text File To Open";
        fd.Filter = "Text Files|*.txt";
        fd.InitialDirectory = @"C:\";
        if (fd.ShowDialog() == DialogResult.OK)
        {
            TextFiles(sender);
        }
    }
    private void TextFiles(object sender)
    {
        IEnumerable<String> employeeNames = File.ReadLines(fd.FileName);
        foreach (string pgs in employeeNames)
        {
            employee = pgs;
            ProcessTables(employee, sender);
        }
    }
    private void ProcessTables(string employee, object sender)
    {
        sw.Restart();
        timer.Start();
        //This line is where the compiler throws the error
        backgroundWorker1.RunWorkerAsync();            
    }
    private void backgroundworker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
      progressBar1.Value = e.ProgressPercentage;
    }
    private void backgroundworker1_DoWork(object sender, DoWorkEventArgs e)
    {
      //Never hits this block so I will omit this code for time sake
    }
}
}

Solution

  • ProcessTables is called in a loop by TextFiles. So you're trying to restart a running BackgroundWorker.

    How to solve this, depends on what you're actually trying to do (you could prepare a "todo list" for a single BackgroundWorker, use multiple BackgroundWorkers, use producer/consumer pattern).