tags:

views:

227

answers:

4

Looking for a way to programticaly dump the call stack and a .net Win Forms app when ever a section of code is hit. Its something I haven't come across before but will save me some debug time.

Update : Forgot to add , how much overhead would this add to the application , i.e. would it slow it down considerably.

+5  A: 
System.Environment.StackTrace

Will give you the current stack as a string.

You can also use the StackTrace class as others have pointed out if you have more advanced needs.

Ryan Cook
+2  A: 
Wim Hollebrandse
A: 

http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx

From MSDN:

using System.Diagnostics;

        StackTrace st = new StackTrace(true);
        for(int i =0; i< st.FrameCount; i++ )
        {
            // Note that high up the call stack, there is only
            // one stack frame.
            StackFrame sf = st.GetFrame(i);
            Console.WriteLine();
            Console.WriteLine("High up the call stack, Method: {0}",
                sf.GetMethod());

            Console.WriteLine("High up the call stack, Line Number: {0}",
                sf.GetFileLineNumber());
        }
Arthur
A: 

Actually it wouldn't slow down your application, because the callstack information mustn't be generated, it's present during the whole processing of your code.

Thomasek
-1: The information to generate a call stack is present, but definitely not stored in an optimal form. The method and type *names* need to be accessed (instead of just their token), the offset in native code has to be mapped to the offset in bytecode, which is then mapped to the position in a file. Overall this is a very expensive operation, and I believe it's the most expensive operation involved in exception handling (not 100% sure on the last part).
280Z28
I don't agree. The most expensive operation is recursing to the depth of the callstack. THe overhead is different if you analyze the first level on the callstack (the 1. call frame) or if you area already in the depth of 20.
Thomasek
See also http://stackoverflow.com/questions/52312/what-is-the-real-overhead-of-try-catch-in-c
Thomasek