6.3. The StackTrace Object
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.
Example 6-5. Iterating the call stack
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
This ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access