Hi everyone,
I have a solution to my problem.
Thanks for your suggestions.
After attempting to implement a lot of different solutions, I think I've found one which is a lot simpler then my original ideas and appears to solve the problem with the least amount of additional code.
public Exception handledException { get; set; }
...
public void Execute(object parameter)
{
BackgroundWorker background = new BackgroundWorker();
background.RunWorkerCompleted += new RunWorkerCompletedEventHandler(background_RunWorkerCompleted);
background.DoWork += delegate
{
try
{
}
catch(Exception ex)
{
ViewModel.handledException = ex;
}
};
background.RunWorkerAsync();
}
void background_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (ViewModel.handledException != null)
{
MessageBox.Show
(
ViewModel.handledException.Message.ToString(),
"Error",
MessageBoxButton.OK,
MessageBoxImage.Error
);
}
else
{
}
}
So with this approach, I have an exception property of my ViewModel class(don't worry I set that variable to null when I call my ClearAll() function at the end of each operation).
If an exception occurs this variable is set. The program exits the
try-catch
and reaches the end of the
DoWork
delegate. Therefore the
RunWorkerCompleted
event is raised. Once this happens all background operations are completed. I did try and manually use the cancel async operation, but I couldn't get that to work.
Once inside that event handler I check to see if my exception property is
null
. If it isn't an exception occurred which I alert the user to and reset the application to it's initial state, if not I set the observable properties that the controls are bound onto, to the values of my collections.
When the message box appears, you can't interact with the window underneath until it's been closed, by which time all of the variable have been cleared and the application is in a stable state.
Thanks for your help everyone. Any feedback on this approach?
Laurence