Stack Frame Inspection Sample
This sample demonstrates how to programmatically retrieve information about the call stack at any point from within the executing code. The stack allows you to determine the sequence of procedures that the application executed before getting to the current procedure.
This sample code is provided to illustrate a concept and should not be used in applications or Web sites, as it may not illustrate the safest coding practices. Microsoft assumes no liability for incidental or consequential damages should the sample code be used for purposes other than as intended.
To open the sample file in Solution Explorer
Click Download Sample.
The File Download message box appears.
Click Open, and on the left column of the zip folder window, click Extract all files.
The Extraction Wizard opens.
Click Next. You can change the directory that the files will be extracted to, and then click Next again.
Make sure that the Show extracted files check box is selected, and click Finish.
Double-click the sample's .sln file.
The sample solution is displayed in Solution Explorer. You might get a security warning that says the solution location is not trusted. Click OK to continue.
To run this sample
The .NET Framework provides the functionality as part of theclass. The sample demonstrates two other classes: and . The parameterless constructor of StackTrace returns a complete set of StackFrame objects, providing information from the time your application started. You can also use the StackTrace constructor that takes an instance. This constructor provides stack trace information back to the code that triggered the exception.
The event handler for the Test Procedure Stack button contains code to call several methods resulting in a stack several levels deep. Clicking the Test Procedure Stack button calls ProcA, which calls ProcB. ProcB calls the GetFullStackFrameInfo procedure, passing in a new StackTrace object:
In the GetFullStackFrameInfo procedure, the code uses theproperty of the StackTrace object to retrieve the total number of stack frames, working backwards from the current procedure. The procedure then adds information about each stack frame to the list box on the sample, calling the method to retrieve an indexed stack frame object.
The GetStackFrameInfo procedure calls GetFrame on the StackFrame object the code sent to it, and then it retrieves properties of the MethodInfo object to display information about the procedure in the list box.
The event handler for the Test Exception Handling button generates an error down the stack several layers. The code triggers an exception and passes that exception to the constructor for the StackFrame object.