【发布时间】:2011-06-05 06:41:55
【问题描述】:
我正在开发一个轻量级的 WPF MVVM 框架,并且希望能够捕获未处理的异常,并在理想情况下从中恢复。
暂时忽略所有不这样做的好论据,我遇到以下情况:
如果我在 App.xaml.cs 的 OnStartup 方法中注册 AppDomain.CurrentDomain.UnhandledException 的处理程序,如下...
App.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 终止应用程序。
我真正想做的是恢复并将控制权返回给主框架 VM。 (再次抛开反对这样做的动机)。
所以,读了一些资料,我决定在同一个地方为 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 的处理程序。
有没有人有办法捕获未处理的 VM 异常并从中恢复?
值得一提的是,框架中没有明确使用线程。
【问题讨论】:
标签: c# wpf exception-handling c#-4.0