简体   繁体   中英

Write stack trace when an exception is thrown from another thread

How can I write the stack trace of an unhandled exception (thrown from any thread) to a file?

I need this to help debug a hanging application.

Take a look at AppDomain.UnhandledException event. It seems that this is exactly what you need.

Thanks you all, but I have seen that when I running the program from Visual Studio the output of trace that is written by .NET to the console window when an unhandled exception from any thread is thrown is not redirected to the console window.

It is just redirected when I run the program separated from Visual Studio. So this code is very good to see all stack trace from any thread that throws an exception which is not handled

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;

I believe you can do this by listening to AppDomain.UnhandledException event. In case of WPF it worth listening to Application.Current.Dispatcher.UnhandledException as well

You can get the stack track in catch block by ex.StackTrace like below:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM