我正在开发一个轻量级 WPF MVVM 框架,并且希望能够捕获未处理的异常,并理想地从中恢复。
暂时忽略所有不这样做的好论据,我遇到以下情况:
如果我在 App.xaml.cs 的 OnStartup 方法中注册 AppDomain.CurrentDomain.UnhandledException 的处理程序,如下所示...
应用程序.xaml.cs:
protected override void OnStartup(StartupEventArgs e)
{
AppDomain.CurrentDomain.UnhandledException += new
UnhandledExceptionEventHandler(this.AppDomainUnhandledExceptionHandler);
base.OnStartup(e);
}
void AppDomainUnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs ea)
{
Exception e = (Exception)ea.ExceptionObject;
// log exception
}
然后在我的虚拟机之一中引发异常,处理程序将按预期调用。
到目前为止一切都很好,除了我无法使用这种方法进行恢复之外,我所能做的就是记录异常,然后让 CLR 终止应用程序。
我实际上想做的是恢复并将控制权返回给主框架虚拟机。 (再次抛开反对这样做的动机)。
因此,进行一些阅读后,我决定在同一位置为 AppDomain.CurrentDomain.UnhandledException 注册一个事件处理程序,以便代码现在看起来像这样......
protected override void OnStartup(StartupEventArgs e)
{
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(this.AppDomainUnhandledExceptionHandler);
this.DispatcherUnhandledException +=
new DispatcherUnhandledExceptionEventHandler(DispatcherUnhandledExceptionHandler);
base.OnStartup(e);
}
void AppDomainUnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs ea)
{
Exception e = (Exception)ea.ExceptionObject;
// log exception
}
void DispatcherUnhandledExceptionHandler(object sender, DispatcherUnhandledExceptionEventArgs args)
{
args.Handled = true;
// implement recovery
}
问题是,一旦我注册了 this.DispatcherUnhandledException 的处理程序,就不会调用任何事件处理程序。因此,注册 DispatcherUnhandledExceptionHandler 会以某种方式停用 AppDomain.CurrentDomain.UnhandledException 的处理程序。
有谁有捕获未处理的虚拟机异常并从中恢复的方法吗?
值得一提的是,框架中没有明确使用线程。