【问题标题】:Write stack trace when an exception is thrown from another thread当从另一个线程抛出异常时写入堆栈跟踪
【发布时间】:2012-11-27 14:29:03
【问题描述】:

如何将未处理异常(从任何线程抛出)的堆栈跟踪写入文件?

我需要这个来帮助调试挂起的应用程序。

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    看看AppDomain.UnhandledException 事件。看来这正是您所需要的。

    【讨论】:

      【解决方案2】:

      谢谢大家,但是我已经看到,当我从 Visual Studio 运行程序时,当抛出来自任何线程的未处理异常时,由 .NET 写入控制台窗口的跟踪输出不会重定向到控制台窗口.

      当我运行与 Visual Studio 分开的程序时,它只是被重定向。 因此,这段代码非常适合查看来自任何抛出未处理异常的线程的所有堆栈跟踪

      Trace.Listeners.Clear();
      
              TextWriterTraceListener twtl = new TextWriterTraceListener(Path.Combine(Environment.CurrentDirectory, "logfile.txt"));
              twtl.Name = "TextLogger";
              twtl.TraceOutputOptions = TraceOptions.ThreadId | TraceOptions.DateTime | TraceOptions.Callstack;
      
              ConsoleTraceListener ctl = new ConsoleTraceListener(false);
              ctl.TraceOutputOptions = TraceOptions.DateTime;
      
              Trace.Listeners.Add(twtl);
              Trace.Listeners.Add(ctl);
              Trace.AutoFlush = true;
      

      【讨论】:

        【解决方案3】:

        我相信您可以通过收听AppDomain.UnhandledException 事件来做到这一点。 如果是 WPF,也值得一听 Application.Current.Dispatcher.UnhandledException

        【讨论】:

          【解决方案4】:

          您可以通过 ex.StackTrace 获取 catch 块中的堆栈跟踪,如下所示:

          try
          {
             //Your code;
          }
          catch(Exception ex)
          {
              string innerException = ex.InnerException;
              string stackTrac = ex.StackTrace;
              //Write this stackTrac to any file where you want
          }
          

          【讨论】:

            猜你喜欢
            • 2012-08-24
            • 1970-01-01
            • 2011-09-27
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2010-10-10
            • 1970-01-01
            相关资源
            最近更新 更多