43

Looking for a way to programmatically 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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
RC1140
  • 8,423
  • 14
  • 48
  • 71
  • 2
    Regarding overhead/performance, see [c# - Dumping the call stack programatically - Stack Overflow](http://stackoverflow.com/questions/1678816/dumping-the-call-stack-programatically) – Stéphane Gourichon Nov 22 '15 at 10:34

4 Answers4

76
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
  • 9,275
  • 5
  • 38
  • 37
15

You can use:

StackTrace callStack = new StackTrace();

And to then access a specific stack frame:

StackFrame frame = callStack.GetFrame(1);
Wim
  • 11,998
  • 1
  • 34
  • 57
1

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
  • 7,939
  • 3
  • 29
  • 46
-3

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.

Tomas Walek
  • 2,516
  • 2
  • 23
  • 37
  • 2
    -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). – Sam Harwell Nov 05 '09 at 07:44
  • 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. – Tomas Walek Nov 05 '09 at 08:53
  • See also http://stackoverflow.com/questions/52312/what-is-the-real-overhead-of-try-catch-in-c – Tomas Walek Nov 05 '09 at 08:55