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?