[Mono-dev] Walking all managed objects

Paolo Molaro lupus at ximian.com
Tue Jul 3 05:27:17 EDT 2007

On 07/02/07 Joachim Ante wrote:
> Is there any way from managed or unmanaged code to iterate through  
> all allocated managed objects?
> I presume the Garbage collector must have this data somewhere?

It does, but the way it does it is not exposed and it will never be
exposed (because it's an internal detail and the user can't perform
the same traversal safely). You can implement something similar
using reflection or the embedded API, by looking at the fields
and iterating their values, though handling recursive references would
be a pain in managed code and not really safe if done in unmanaged code
(you can't stop the world and this means the mutator threads can change
references under you or a GC can happen or many other things can go
wrong...). You'll be able to do this only for GC root you keep track of
yourself, though.

> I basically want to see which objects are being referenced and then  
> unload some unmanaged data based on it.
> I don't want to override the finalizer for performance reasons. In  
> our situation there are specific times where i can just spend a bunch  
> of time on cleanup.

It sounds like you want to get weak references to the interesting
objects (mono_gchandle_new_weakref() in the embedded API or the
low-level GCHandle in managed code) and put them in an array:
when the time comes you iterate the handles and check the ones that
have a null target, meaning the object was collected and perform your
cleanup, including freeing the GC handle. This lets you decide when to
do the cleanup which seems to be one of your concerns (this solution
should be a little cheaper than finalizers and definitely cheaper than
doing the tarversal yourself or using the profiler interface as was
suggested which have the additional issues detailed above).


lupus at debian.org                                     debian/rules
lupus at ximian.com                             Monkeys do it better

More information about the Mono-devel-list mailing list