加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在FrameWork级别捕获WPF中的异常

发布时间:2020-12-16 01:40:11 所属栏目:百科 来源:网络整理
导读:我正在开发一个轻量级的 WPF MVVM框架,并且希望能够捕获未处理的异常,并且理想地从它们中恢复. 暂时忽略所有不这样做的好论据,我遇到以下情况: 如果我在App.xaml.cs的OnStartup方法中注册AppDomain.CurrentDomain.UnhandledException的处理程序,如下所示…
我正在开发一个轻量级的 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
}

然后在我的一个VM中引发异常,处理程序按预期调用.

到目前为止这么好,除了我无法使用这种方法恢复的事实,我所能做的就是记录异常,然后让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异常中捕获和恢复?

值得一提的是,框架中没有明确使用线程.

解决方法

VS向您展示异常的原因是因为您已将其设置为相同(要么您明确地这样做了 – 或者更可能 – VS中的默认值就像这样配置它).您可以通过Debug-> Exceptions菜单控制Visual Studio在调试代码中遇到异常时所执行的操作.

即使你有一个捕获它,你甚至可以让它打破,这在某些情况下非常方便.

如果您没有使用多线程,那么您应该使用DispatcherUnhandledException事件,因为它将捕获在主UI线程上未被捕获的所有内容.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读