Search code examples
c#winformsbackgroundworkerwaitautoresetevent

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

Solution

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