我正在开发一个轻量级WPF MVVM框架,并希望能够捕获未处理的异常,并从中理想地恢复。在框架级别捕获WPF异常
暂时忽略所有的很好的理由不这样做,我会遇到以下情况:
如果我的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终止应用程序。
我真正想要做的是恢复,并返回到主框架虚拟机的控制。 (再次摒弃这样做的动机)。
所以,做一些阅读,我决定在同一个地方登记为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异常中捕获和恢复?
提到在框架中没有明确使用线程可能很重要。
谢谢Isak,知道我会捕获所有可能产生的异常是很重要的。 – 2011-01-07 19:11:44