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

Nik*_*rth 5 .net c#

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

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

Nik*_*rth 1

谢谢大家,但我发现,当我从 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;
Run Code Online (Sandbox Code Playgroud)