I've got a BackgroundWorker
that occasionally needs to call into the UI thread to perform some work and retrieve a result. To achieve this I'm using the following from within the background thread:
App.Current.Dispatcher.Invoke(new Action(() => { /* some code that updates local data */ });
As the app is exiting, I want to be able to tell the BackgroundWorker
to quit but I want to allow it to finish any current operations. In other words, I want to call BackgroundWorkerObj.CancelAsync()
and then pump messages until the thread has exited.
I've tried the following, but the Invoke()
in the background thread still blocks (though the UI thread is still churning):
Worker.CancelAsync();
while (Worker.IsBusy)
{
DispatcherFrame Frame = new DispatcherFrame();
Frame.Continue = false;
Dispatcher.PushFrame(Frame);
}
What's the correct way to do this? How can the UI thread wait on the BackgroundWorker
while still executing Invokes from that BackgroundWorker
object?