【问题标题】:New HandleProcessCorruptedStateExceptions attribute in .NET 4.NET 4 中的新 HandleProcessCorruptedStateExceptions 属性
【发布时间】:2010-06-02 06:27:30
【问题描述】:

我正在尝试使我的WPF 应用程序崩溃,并使用上述新的 .NET 4 属性捕获异常。

我设法通过调用Environment.FailFast("crash"); 手动使我的应用程序崩溃。 (我还设法使用来自“How to simulate a corrupt state exception in .NET 4?”的 Hans 的代码使其崩溃。)

当按下按钮时,应用程序会调用上述崩溃代码。 这是我的异常处理程序:

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException;
        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

        DispatcherUnhandledException += app_DispatcherUnhandledException;
    }

    [HandleProcessCorruptedStateExceptions]
     void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        //log..
    }

    [HandleProcessCorruptedStateExceptions]
     void CurrentDomain_FirstChanceException(object sender, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e)
    {
        //log..
    }

    [HandleProcessCorruptedStateExceptions]
     void app_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
    {
        //log..
    }

上面显示的//log... 评论仅用于说明;那里有真正的日志记录代码。

在 Visual Studio 中运行时,会引发异常,但不会“冒泡”到那些异常处理程序块。 当独立运行时(没有附加调试器),我没有得到任何日志,尽管我期望。

为什么会这样,如何让处理代码被执行?

【问题讨论】:

  • 也许您还需要将 [SecurityCritical] 添加到您的处理程序中。

标签: .net exception exception-handling crash


【解决方案1】:

该属性必须放在包含 try/catch 的方法中,而不是放在事件处理程序中。

我对@9​​87654321@的回答中提供了一个示例

【讨论】:

  • 不,这两个 AppDomain 事件的注释都没有说您可以在事件处理程序上使用它。 OP 只是缺少同样需要的 SecurityCritical 属性。
【解决方案2】:
  1. FailFast() 的目的是立即退出,这就是不调用处理程序的原因。
  2. 甚至某些“损坏状态异常”也无法被这些处理程序捕获 - 一个重要的示例是 StackOverflowException(我实际上尝试在 ASP.NET 应用程序中捕获一个异常,但它不起作用,尽管该属性存在)。

答案基于这篇文章:www.naveenbhat.in/2013/02/tips-and-tricks-of-exception-handling_28.html

【讨论】:

    【解决方案3】:

    事件处理程序必须同时标记[HandleProcessCorruptedStateExceptions][SecurityCritical] 才能触发事件处理程序。这个要求在FirstChanceExceptionUnhandledException的备注部分都有提到。

    DispatcherUnhandledException 的评论并未说明您可以在其中处理损坏的状态异常,因此该事件可能无法处理。

    在备注中还要注意,强烈建议您在受约束的执行区域内创建FirstChanceException,以防止堆栈溢出或内存不足异常的无限循环。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-26
      • 1970-01-01
      • 2010-10-30
      • 2013-02-12
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 2011-01-10
      相关资源
      最近更新 更多