1

我有一个带有以下代码的 Windows 服务

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

private static void CurrentDomain_FirstChanceException(object sender, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e)
    {
          if (e.Exception == null)
            return;

          LogException(e.Exception, "FirstChance Exception ");
    }

    public void Test()
    {
      Task.Factory.StartNew(x =>
            {
               foreach(item in blockingCollection.GetConsumingEnumerable())
               {
                  try
                  {
                     Convert.ToInt32("Test");
                  }
                  catch (Exception ex)
                  {
                  }
               }
            });            
        }

在测试方法捕获内部,我可以看到完整的堆栈跟踪

 at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
   at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
   at System.Convert.ToInt32(String value)
   at Test.TestService.<QueueConsumer>b__11_0(Object x) in C:\SourceControl\TestProject.Risk\Application\TestService.cs:line 157

而在private static void CurrentDomain_FirstChanceException我看到不完整的堆栈跟踪

System.FormatException: Input string was not in a correct format.
   at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)

如果我删除try{}catch{}CurrentDomain_UnhandledException 事件不会被触发

我想避免 try{}catch{} 只是为了记录异常。如何在第一次机会异常中获得完整的堆栈跟踪?

4

0 回答 0