等待 BackgroundWorker 完成,如果 运行,在 FormClosing 时间

Wait for BackgroundWorker finish, if running, at FormClosing time

如何等待 BackgroundWorker to finish, if running, when the user request to close application? I'd like to wait to this BackgroundWorker finish then exit application. I tried with AutoResetEvent but a call to WaitOne() at FormClosing time seems to block the entire UI and doesn't fire RunWorkerCompleted event where Set() 被调用。 我怎样才能做到这一点?

我正在为此寻找 alternative/proper 方法:

bool done = false;
        private void my_backgroundWorker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            resetEvent.Set();
            done = true;
        }

        private void myForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (notify_backgroundWorker.IsBusy)
            {
                while(!done)
                {
                    Application.DoEvents();
                    Thread.Sleep(500);
                }
                //resetEvent.WaitOne();
            }
        }

不用弄那么复杂,有一个class级变量就可以了

bool quitRequestedWhileWorkerBusy=false;

如果用户试图关闭表单,在表单关闭事件中检查工作人员是否忙碌,取消事件并设置quitRequestedWhileWorkerBusy=true

在您的工作人员完成事件中,if(quitRequestedWhileWorkerBusy) this.Close();

另一种方法是基于 OP 的示例代码,但经过简化:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    // Stop the background worker thread (if running) to avoid race hazard.
    if (backgroundWorker1.IsBusy)
    {
        backgroundWorker1.CancelAsync();

        // Wait for the background worker thread to actually finish.
        while (backgroundWorker1.IsBusy)
        {
            Application.DoEvents();
            Thread.Sleep(100);
        }
    }
}