Jack Jack - 1 year ago 36
C# Question

Wait for BackgroundWorker finish, if running, at FormClosing time

How can I wait for

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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download