Niklaus Wirth
Niklaus Wirth

Reputation: 870

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.

Upvotes: 5

Views: 643

Answers (4)

Niklaus Wirth
Niklaus Wirth

Reputation: 870

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;

Upvotes: 1

Rohit Vyas
Rohit Vyas

Reputation: 1959

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
}

Upvotes: 0

Sergey Teplyakov
Sergey Teplyakov

Reputation: 11647

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

Upvotes: 4

sll
sll

Reputation: 62484

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

Upvotes: 0

Related Questions