简体   繁体   English

使用backgroundworker时出错

[英]Error on using backgroundworker

//This is my code //这是我的代码

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

There is no error on execution of the process on the first click, but when i try to click the command button (btnGenSumm) again to repeat the processs, I got error "value dispose cannot be called while doing createhandle"., Please help me with this. 第一次单击时执行该过程没有错误,但是当我再次尝试单击命令按钮(btnGenSumm)以重复该过程时,出现错误“在执行createhandle时不能调用值处理”。,请帮助我有了这个。

I would always create a new worker before starting a task; 在开始执行任务之前,我总是会创建一个新的工作人员。 this avoids those issues. 这样可以避免这些问题。

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
}

Using this approach there is no way that the worker can ever be accessed while it is running and you are guaranteed that whenever the user clicks the button the last worker has completed and there is no nasty IsBusy fudge. 使用这种方法,无法在工作进程运行时访问该工作进程,并且可以保证,只要用户单击该按钮,最后一个工作进程IsBusy完成,并且不会出现讨厌的IsBusy软糖。

UPDATE 更新

Explicitly WorkerFactory does something like this 明确地, WorkerFactory做这样的事情

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

    return worker;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM