Ant*_*ttu 6 wpf exception-handling mvvm-light
我正在尝试在使用MVVM Light Toolkit构建的WPF应用程序中创建一个简单的全局异常处理程序,但我很难让它工作.
问题是视图模型中出现的异常不会被App的UnhandledException处理程序捕获,即使我为Dispatcher和AppDomain注册一个侦听器,如下所示:
private void Application_Startup(object sender, StartupEventArgs e)
{
AppDomain.CurrentDomain.UnhandledException += DomainUnhandledException;
DispatcherUnhandledException += App_DispatcherUnhandledException;
}
private void DomainUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs)
{
var exception = unhandledExceptionEventArgs.ExceptionObject as Exception;
ShowExceptionMessage(exception);
}
private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
ShowExceptionMessage(e.Exception);
e.Handled = true;
}
Run Code Online (Sandbox Code Playgroud)
我发现这个博客文章描述了问题点,使用此代码描述的解决方案剪切了视图模型:
// Throw the exception in the UI thread.
App.Current.RootVisual.Dispatcher.BeginInvoke(() => { throw new MyException(); });
Run Code Online (Sandbox Code Playgroud)
但是,我希望所有异常都冒泡到全局异常处理程序,而不仅仅是我自己在VM中抛出的异常处理程序.
所以问题是:在某个地方以某种方式将异常从其他线程重新抛入UI线程吗?
更新:为App的事件处理程序设置添加了更详细的代码.