Monday, January 2, 2012

How to get call stack programmatically?



StackTrace class is useful to get an execution call stack of running program.  StackTrace class provides information which is useful while debugging application. StackFrame class contains useful information like filename, line number and column number. StackFrame is created while execution of program on every method calls. StackFrame information will be the most useful while debugging application. StackTrace and StackFrame class are available inside System.Diagnostics namespace


Let’s have a look on below code.


public class StackTraceTest
{
    public StackTraceTest()
    {
    }

    public void method1()
    {
        method2();
    }
    public void method2()
    {
        method3();
    }
    public void method3()
    {
        try
        {
            throw new Exception("An error occured");
        }
        catch (Exception ex)
        {
            StackTrace st = new StackTrace(true);
            Console.WriteLine("Call Stack :");

            foreach (StackFrame sf in st.GetFrames())
                Console.WriteLine("File: {0}, Method: {1}, 
                    Line: {2}, Column: {3}, Offset: {4}"
                    sf.GetFileName(),
                    sf.GetMethod().Name,
                    sf.GetFileLineNumber(),
                    sf.GetFileColumnNumber(),
                    sf.GetILOffset()
                    );
        }
    }
}

public static void main()
{
    StackTraceTest stest = new StackTraceTest();
    stest.method1();
}

Output

File: StackTraceDemo.xaml.cs, Method: method3, Line: 52, Column: 13, Offset: 21
File: StackTraceDemo.xaml.cs, Method: method2, Line: 42, Column: 9, Offset: 7
File: StackTraceDemo.xaml.cs, Method: method1, Line: 38, Column: 9, Offset: 7

As per above output, StackTrace and StackFrame class are providing useful information while debugging. GetFrames method returns collection of StackFrame classes. Each stackframe instance provides information like method name, file name, line number, column number, offset etc.


Below is the snapshot of CallStack window from Visual Studio



See Also – 

No comments:

Post a Comment