从另一个线程抛出exception时写入堆栈跟踪

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

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

看一下AppDomain.UnhandledException事件。 看来这正是你所需要的。

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

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

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; 

我相信你可以通过监听AppDomain.UnhandledException事件来做到这一点。 在WPF的情况下,它也值得收听Application.Current.Dispatcher.UnhandledException

您可以通过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 }