0

How can I wait for 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() is called. How can I accomplish this?

I'm looking for an alternative/proper way for this:

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();
            }
        }
Jack
  • 16,276
  • 55
  • 159
  • 284
  • 1
    See [How to stop BackgroundWorker on Form's Closing event?](https://stackoverflow.com/q/1731384/719186) – LarsTech Jul 26 '17 at 19:30

2 Answers2

1

No need to make it so complex, just have a class level variable

bool quitRequestedWhileWorkerBusy=false;

If the user tried to close the form, in the form closing event check if the worker isbusy, cancel the event and set quitRequestedWhileWorkerBusy=true

In your worker completed event, if(quitRequestedWhileWorkerBusy) this.Close();

Caius Jard
  • 72,509
  • 5
  • 49
  • 80
0

Another way is based on OP's sample code, but simplified:

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);
        }
    }
}
Dave C
  • 186
  • 1
  • 3