Telling where we are in the stack

  • Thread starter Thread starter Joshua Frank
  • Start date Start date
J

Joshua Frank

Hi All,

I'm trying to use this to determine which method called my method. I
have two ways, but neither is quite right:

Method 1:

Sub WhereAreWe()
Dim sf As New System.Diagnostics.StackFrame(1, True)
...
End Sub

But in this code

1 Sub Test()
2 WhereAreWe()
3 WhereAreWe()
4 End Sub

the stack frame is different in each WhereAreWe call, in that the first
time it knows that the caller is on line 2 and the second it knows that
it's on line 3. I can get around this by using StackFrame.GetMethod,
but then I get a different problem:

Method 2:

1 Sub RecursionTest()
2 If ReachedBottom Then Exit Sub
3
4 WhereAreWe()
5 RecursionTest()
6 End Sub

When I do this, the WhereAreWe function has no way of telling where,
exactly, we are, because GetMethod is the same for regardless of how
many frames deep we are in the recursive call stack.

So, is there any way to tell where we are, solving both of these
problems at once? TIA.

Cheers,
Josh
 
So, is there any way to tell where we are...


No matter where you go, there you are.

StackTrace st = new StackTrace(true);
StackFrame callingFrame = st.GetFrame(1);
string name = callingFrame.GetMethod().Name;

Just check the (+1) stack frame to find your immediate caller. If you're
concerned that there may be recursion, and you want to know the first
non-recursive caller, you'll need to traverse the stack frames looking for
the first method name that isn't equal to the immediate caller.
 
Thanks, I'll give that a try. Incidentally, getting the stack has at
least two disadvantages for my application:

1. I suspect it's a little slow (I'm doing something that runs all the
time, not just in an error situation.
2. What I'd really like is to know when the stack frame terminates, but
there's no way to use the StackFrame class for this. In other words, I
want to get the current frame and then somehow be notified when the
stack is popped, i.e., when the method is finished.

Would you happen to know a way to address these two points? TIA.

Cheers,
Josh
 
Back
Top