【问题标题】:Stacktrace reported by UnhandledExceptionEventArgs exception becomes null after extracting onceUnhandledExceptionEventArgs异常上报的Stacktrace提取一次后变为null
【发布时间】:2025-12-06 00:00:01
【问题描述】:

我有一个 Windows Phone 8.1 RT 应用程序。在应用程序中,我订阅了UnhandledException 事件,当应用程序中发生任何未处理的异常时会引发该事件。我将此事件绑定到一个事件处理程序,该处理程序由事件传递UnhandledExceptionEventArgs

UnhandledExceptionEventArgs 有一个属性Exception,它有一个属性Stacktrace。问题是,我只能访问堆栈跟踪属性一次,因为在我访问它后它变为空。

当任何断点被命中并且您尝试使用光标或即时窗口访问参数中包含的值时,也可以观察到这种奇怪的行为。一旦我将光标悬停或访问即时窗口中的值,它就会变为空。

当我在读取Stacktrace 属性之前读取UnhandledExceptionEventArgs 的任何属性时,也会导致问题。假设e 是包含MessageException 对象的UnhandledExceptionEventArgs 类型,则在访问e.Exception.Stacktrace 之前访问e.Message 会使e.Exception.Stacktrace 中包含的值为空。

知道为什么会观察到这种奇怪的行为吗?

【问题讨论】:

    标签: c# windows-runtime windows-phone-8.1 winrt-xaml


    【解决方案1】:

    不确定是不是这样,但MSDN 说:

    UnhandledException 事件参数公开一个异常对象 通过 Exception 属性。但是,类型、消息和堆栈 不保证此异常对象的跟踪与 引发的原始异常

    【讨论】:

    • 我知道那里提到的限制,但我想这不是这种情况下的问题。如果暴露的异常对象有一个堆栈跟踪,它应该可以访问。堆栈跟踪的可见时间不够长。消息和类型保持不变,但堆栈跟踪在单次访问后变为空。
    【解决方案2】:

    这似乎是一个问题:Improper WinRT exception behavior

    在读取 UnhandledExceptionEventArgs 类的任何属性之前,您应该将 UnhandledExceptionEventArgs.Exception 值保存到变量中。 之后,您可以通过读取变量值(不是 UnhandledExceptionEventArgs.Exception 值)随时访问任何信息(如堆栈跟踪)。

    【讨论】:

      【解决方案3】:

      尝试使用属性UnhandledExceptionEventArgs.Message

      比较

      Application.Current.UnhandledException += (sender, args) =>
      {
          Debug.WriteLine(args.Exception.ToString()); // {"Exception of type 'System.Exception' was thrown."}
          Debug.WriteLine(args.Exception.Message); // "Exception of type 'System.Exception' was thrown."
          Debug.WriteLine(args.Message); // "System.Exception: Exception of type 'System.Exception' was thrown.\r\n   at AppMetrica.Demo.MainPage.<>c.<.ctor>b__0_2(Object sender, RoutedEventArgs args)"
      };
      

      【讨论】:

      • 不幸的是 args.Message 并不总是包含堆栈跟踪