Lets say I have 3 classes:
class A {
void do_A() {
//Check object call hierarchy
}
}
class B {
void do_B() {
A a;
a.do_A();
}
}
class C {
void do_C() {
B b;
b.do_A();
}
}
And then I call:
C c;
c.do_C();
How can i get the object call hierarchy from within A’s do_A() ?
I mean I want to get the references of object in a.do_A() (can be easily attained by this), the reference of object b that called a.do_A(), and the reference of object c that called b.do_B().
I think this should be possible, because I can get the call hierarchy with call stack, so I’m sure I should be able to get some more information about the objects who called the methods.
In general, what you ask for is not possible in .NET – even in theory. Perhaps unintuitively, there’s no guarantee that an object is still alive even when an instance-method on that object is in the midst of execution. Essentially, the CLR is smart enough to recognize when the hidden
thisreference passed to an instance-method will no longer be dereferenced. The referenced object can then become eligible for collection when this happens (assuming it is not reachable through other roots, of course).As a corollary, it’s also perfectly possible for a “calling object” to be dead while the method it has called is still executing. In your specific example, it’s perfectly possible that
bandc(really the objects referred to by those variables) don’t exist anymore whileA.do_A()is executing.What this means of course is that the information you seek may no longer be available in any form in the process, and no “magic” API should be able to reliably produce it.
I recommend reading Raymond Chen’s article: When does an object become available for garbage collection? to understand this issue better:
If you feel this doesn’t relate to your question, consider the second-last paragraph in that article: