I’m trying to understand where an important object gets his destructor called.
I made an explicit one, in order to log the stacktrace that lead to it.
But new StackFrame(1).GetMethod().Name; throws a NullReferenceException and I’m not sure i can use that approach since the Destructor (~MyClass(){}) isn’t explicitely called by the application (anyway, i think you can’t).
Is there any way to know the stacktrace leading to the destruction of an object?
Thanks!
Finalizers (which is what you’re writing, they’re not destructors, even though they might use the same syntax as destructors in C++ do) are invoked on a thread owned by the Garbage Collector. There is nothing in the stack trace relevant to you, even if you could get at it.
There is in general no way to know what events lead to the destruction of an object, since object destruction is nondeterministic in .NET. The GC checks occasionally to see what objects are still reachable. Any object that is not reachable has its memory deallocated. Nowhere is kept track what the last live reference to an object was.