wpf - MVVM Light 应用程序的全局异常处理程序

标签 wpf exception-handling mvvm-light

我正在尝试在使用 MVVM Light Toolkit 构建的 WPF 应用程序中创建一个简单的全局异常处理程序,但我很难让它工作。
问题是 View 模型中出现的异常不会被应用程序的 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;
}
我找到了this blog post描述了问题点,并为 View 模型截取了这段代码描述的解决方案:
// Throw the exception in the UI thread.
App.Current.RootVisual.Dispatcher.BeginInvoke(() => { throw new MyException(); });
但是,我希望所有异常都冒泡到全局异常处理程序中,而不仅仅是那些我自己扔进 VM 中的异常。
所以问题是:是否有可能以某种方式将其他线程的异常重新抛出到一个地方的 UI 线程中?
更新 :为应用程序的事件处理程序设置添加了更详细的代码。

最佳答案

我想我现在想通了。

问题是由于 WPF 抑制了 View 数据绑定(bind)中引发的异常,并且因为我的 View 模型数据绑定(bind)到 View 的 DataContext(通过我的 ViewModelLocator 中的属性使用统一依赖注入(inject)器) View 模型构造中的任何异常都会被吞噬。

this SO question了解更多信息。

所以我想我只需要确保在构造函数中不会发生对应用程序正常运行能力重要的事情。

关于wpf - MVVM Light 应用程序的全局异常处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10833747/

相关文章:

.net - 数据重置后扩展器崩溃

WPF 功能区 ImageSource

c# - DataGrid 的混淆行为

c# - Ninject WithConstructorArgument : No matching bindings are available, 并且该类型不可自绑定(bind)

c# - 实现通用自定义异常的优缺点

c# - 使用 MvvmLight.Messaging.Messenger 实例化新的 View + ViewModel (Window)

wpf - 如何将DataTemplate添加到资源中?

c# - 绑定(bind)到相关(详细)集合中第一项的属性

.net - 当它们共享相同的类型时如何区分两个 .NET 异常?

c# - 使用 MVVM 和子窗口进行依赖注入(inject)