Jack Jack - 1 year ago 43
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
finish then exit application. I tried with
but a call to
at FormClosing time seems to block the entire UI and doesn't fire RunWorkerCompleted event where
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)
done = true;

private void myForm_FormClosing(object sender, FormClosingEventArgs e)
if (notify_backgroundWorker.IsBusy)

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