C# 使用backgroundworker时出错

C# 使用backgroundworker时出错,c#,C#,//这是我的密码 private void btnGenSumm_Click(object sender, EventArgs e) { if (backgroundWorker1.IsBusy != true) { btnGenSumm.Enabled = false; btnExpSum.Enabled = false; btnClose.Enabled = false; pBox1.Visible = true

//这是我的密码

private void btnGenSumm_Click(object sender, EventArgs e)
{
    if (backgroundWorker1.IsBusy != true)
    {
        btnGenSumm.Enabled = false;
        btnExpSum.Enabled = false;
        btnClose.Enabled = false;
        pBox1.Visible = true;
        backgroundWorker1.RunWorkerAsync();
    }
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
        BackgroundWorker worker = sender as BackgroundWorker;
        loadSummSales(); // this is the process
        System.Threading.Thread.Sleep(50);
}

private void backgroundWorker1_RunWorkerCompleted(object sender, 
    RunWorkerCompletedEventArgs e)
{
        pBox1.Visible = false;
}

在第一次单击时,进程的执行没有错误,但当我尝试再次单击命令按钮(btnGenSumm)以重复该进程时,出现错误“在执行createhandle时无法调用value dispose”。请帮助我解决此问题。

在开始任务之前,我始终会创建一个新的工作进程;这避免了这些问题

private void btnGenSumm_Click(object sender, EventArgs e)
{
    // WorkerFactory creates your worker and hooks up the DoWork 
    // and RunWorkerCompleted events
    var backgroundWorker1 = WorkerFactory();

    // ...
    // Disable access to this Click event in the UI here

    backgroundWorker1.RunWorkerAsync();
}

private void backgroundWorker1_RunWorkerCompleted(
    object sender, 
    RunWorkerCompletedEventArgs e)
{
    // Re-enable access to the Click event in the UI here
}
使用这种方法,无法在worker运行时访问它,您可以保证,每当用户单击按钮时,最后一个worker都已完成,并且没有讨厌的
IsBusy
fudge

更新

明确地说,
WorkerFactory
执行类似的操作

private BackgroundWorker WorkerFactory()
{
    var worker = new BackgroundWorker();
    worker.DoWork += backgroundWorker1_DoWork;
    worker.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;

    return worker;
}

你从哪里得到例外?(另外,请更加努力地格式化您的问题-您的代码到处都是。)protected override void Dispose(bool disposing){if(disposing&&(components!=null)){components.Dispose();}base.Dispose(disposing);}我认为问题不在于Backgroundworker,可能是loadSummSales()逻辑中的问题。要测试注释loadSummSales()并重试