Whenever a method call is made, the Common Language Runtime creates information about that call. This information includes the location of the call within your program, the arguments that have been passed, and the local variables of the target method. The information is saved in a block of data called a stack frame. These stack frames are allocated in a region of memory called the call stack. The call stack contains all the methods that were called but have not returned to their callers. You saw this output to the console in Example 6-4.
This information can be very helpful when you track down bugs in your code. Even more helpful is the fact that you can inspect the call stack programmatically whenever you want. Example 6-5 demonstrates the process of iterating the call stack to obtain the method names that are currently active.
Imports System Imports System.Diagnostics Imports System.Reflection Public Class StackTest Public Sub MethodA( ) MethodB( ) End Sub Public Sub MethodB( ) MethodC( ) End Sub Public Sub MethodC( ) Dim i As Integer = 0 Dim st As New StackTrace( ) For i = 0 To st.FrameCount - 1 Dim sf As StackFrame = st.GetFrame(i) Console.WriteLine(sf.GetMethod.Name) Next i End Sub End Class Public Class Application Public Shared Sub Main( ) Dim test As New StackTest( ) test.MethodA( ) Console.ReadLine( ) End Sub End Class
The output from this program looks like this:
MethodC MethodB MethodA Main