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

时间:2017-07-26 19:22:42

标签: c# winforms backgroundworker wait autoresetevent

如果用户请求关闭应用程序,如何运行,如何等待BackgroundWorker完成?我想等到BackgroundWorker完成然后退出应用程序。我尝试使用AutoResetEvent,但在FormClosing时调用WaitOne()似乎会阻止整个用户界面,并且不会触发调用Set()的RunWorkerCompleted事件。 我怎么能做到这一点?

我正在寻找替代/正确的方法:

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

2 个答案:

答案 0 :(得分:1)

不需要让它如此复杂,只需要一个类级变量

>>> a = b = [1, 2, 3]    
>>> a[:] = a[:2]  # Updates the object in-place, hence affects all references.
>>> a, b
([1, 2], [1, 2])
>>> id(a), id(b)
(4370940488, 4370940488)  # Both still point to the same object

如果用户尝试关闭表单,请在表单结束事件中检查工作人员是否忙碌,取消该事件并设置bool quitRequestedWhileWorkerBusy=false;

在您的工作人员完成的活动quitRequestedWhileWorkerBusy=true

答案 1 :(得分:0)

另一种方法基于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);
        }
    }
}