WPF - error handling with asynchronous command using BackgroundWorker
I'm using the AsyncDelegateCommand
class from this blog post but I'm having trouble knowing what to do with exceptions that occur in my action
delegate. I create the following开发者_开发问答 command:
new AsyncDelegateCommand(
readFile, // action to perform
() => shouldReadFile, // can the action be executed?
obj => readFileFinished(true), // run after action successfully completed
ex => readFileFinished(false) // run after action failed
)
I was expecting any exceptions thrown in my readFile
method to get caught and for the Error
property of RunWorkerCompletedEventArgs to be set, for me to access in my BackgroundWorker.RunWorkerCompleted
handler. However, when I run my app, I get stopped on one of the exceptions that readFile
throws, so I never make it to my handler for RunWorkerCompleted
. Here's my AsyncDelegateCommand
constructor:
public AsyncDelegateCommand(Action action, Func<bool> canExecute,
Action<object> completed, Action<Exception> error)
{
if (null == action)
{
throw new ArgumentNullException("action");
}
_worker.DoWork += (sender, e) =>
{
CommandManager.InvalidateRequerySuggested();
// This can possibly throw an exception:
action();
};
_worker.RunWorkerCompleted += (sender, e) =>
{
if (null != completed && null == e.Error)
{
completed(e.Result);
}
// I never make it here:
if (null != error && null != e.Error)
{
error(e.Error);
}
CommandManager.InvalidateRequerySuggested();
};
_canExecute = canExecute;
}
What I would like is for any exception that action
throws to be caught and stuffed into Error
for handling in RunWorkerCompleted
. How do I achieve this?
Arrgh, never mind, it's Visual Studio doing stuff for me:
If the operation raises an exception that your code does not handle, the BackgroundWorker catches the exception and passes it into the RunWorkerCompleted event handler, where it is exposed as the Error property of System.ComponentModel.RunWorkerCompletedEventArgs. If you are running under the Visual Studio debugger, the debugger will break at the point in the DoWork event handler where the unhandled exception was raised.
-- BackgroundWorker.DoWork Event
I was running my app with the debugger in VS.
精彩评论