Exiting app while async operation in progress?

D

David Veeneman

What's the best way to gracefully exit an app while an asynchronous
operation is in progress?

Let's say I have spawned a worker thread using the BackgroundWorker
component. If I exit the application while the worker thread is running, the
app crashes. It doesn't do any good to call CancelAsync() on the worker
thread from a FormClosing event handler--Since the worker thread is running
asynchronously, the main thread will continue the shutdown without waiting
for the cancel to complete.

I could work up some kludge, like cancelling the FormClose, putting a flag
in as a member variable, then reading that in the RunWorkerCompleted()
handler and reinitiating the application shutdown from there. But that seems
awfully clumsy--There must be a more elegant way to pause the application
shutdown until the worker thread ends.

Any ideas? Thanks.
 
D

David Veeneman

I never did find a great answer to this problem. Here is what I ended up
doing:

(1) I did create a FormClosing method to exit the application. In it, I test
the BackgroundWorker to see if it is busy. If it isn't, the FormClose
proceeds normally. If the BackgroundWorker is busy, the FormClose is
cancelled, the background operation is cancelled, and a flag is set that
tells the RunWorkerCompleted() event handler that we are in the middle of a
form close. Here is the code:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// Defer closing if background operation in process
if (m_BackgroundWorker.IsBusy)
{
// Cancel here
e.Cancel = true;

// Cancel background process
m_BackgroundWorker.CancelAsync();

// Set member variable flag to trigger exit in RunWorkerCompleted()
m_ExitAppCalled = true;
}
}

And here is the line I add at the end of the RunWorkerCompleted() event
handler:

// Exit if we're in the middle of an 'exit app' call
if (m_ExitAppCalled) Application.Exit();

Still not quite as elegant as I'd like, but it works!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top