Jack
Jack

Reputation: 16724

Wait for BackgroundWorker finish, if running, at FormClosing time

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

Upvotes: 0

Views: 631

Answers (2)

Dave C
Dave C

Reputation: 316

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

Upvotes: 0

Caius Jard
Caius Jard

Reputation: 74605

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

Upvotes: 1

Related Questions