BackgroundWorker 当前正忙,无法 运行 并发执行多个任务

BackgroundWorker is currently busy and can not run multiple tasks concurrently

我在使用 backgroundworker 时尝试迭代一个数组,我确信这只是我的语法不正确,但我不断收到错误消息。有人可以帮助我解决这个问题吗?

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
    }
}
}

可能您通过单击 btn_Two 调用了 BackgroundWorker 两次。您应该在 BackgroundWorker 忙碌时禁用按钮。

private void ProcessTables(string employee, object sender)
    {
        sw.Restart();
        timer.Start();
        btn_Two.Enable = false;
        backgroundWorker1.RunWorkerAsync();            
    }

并且您应该在启用按钮的位置添加 backgroundWorker Comleted 事件处理程序。像这样

private void backgroundWorker1_RunWorkerCompleted(
    object sender, RunWorkerCompletedEventArgs e)
{
    btn_Two.Enable = true;
}

ProcessTablesTextFiles 在循环中调用。所以你正在尝试重新启动 运行 BackgroundWorker.

如何解决这个问题,取决于您实际尝试做什么(您可以为单个 BackgroundWorker 准备一个 "todo list",使用多个 BackgroundWorker,使用 producer/consumer 模式).