它是安全的,但会破坏您现有的全局异常处理。在我进行重构之后,我再也没有看到任何错误对话框,为了解决这个问题,我必须订阅 Coroutine.Completed 事件:
Coroutine.Completed += (s, a) =>
{
//Do something here ...
};
您可以在 App.xaml.cs 文件中执行此操作。
我的代码中关于如何处理我的应用程序中出现的所有可能错误的示例:
protected override void OnStartup(StartupEventArgs e)
{
SetupExceptionHandlers();
base.OnStartup(e);
}
private void SetupExceptionHandlers()
{
AppDomain.CurrentDomain.UnhandledException += (s, a) =>
{
HandleException((Exception)a.ExceptionObject, "AppDomain.CurrentDomain.UnhandledException");
};
Current.DispatcherUnhandledException += (s, a) =>
{
HandleException(a.Exception, "Application.Current.DispatcherUnhandledException");
a.Handled = true;
};
TaskScheduler.UnobservedTaskException += (s, a) =>
{
Dispatcher.InvokeAsync(() => HandleException(a.Exception, "TaskScheduler.UnobservedTaskException"));
a.SetObserved();
};
Coroutine.Completed += (s, a) =>
{
if (a.Error != null)
{
HandleException(a.Error, "Coroutine.Completed");
}
};
}
private void HandleException(Exception exception, string source)
{
logger.Error(exception, "Unhandled exception occured (Source: {0})", source);
var msg = new ShowErrorDialogEvent(exception, exception.GetBaseException().Message);
eventAggregator.PublishOnUIThread(msg);
}
如果您想知道,logger 和 eventAggregator 变量是在调用 DisplayRootViewFor 之前从引导程序类中的 OnStartup 方法实例化的。