Delete all references of one object

S

Stefan Borst

Hello,

i want to delete ALL references of one object. So, i first want to get all
references of one object and then delete them(the refernces). A pseudocode
could look like this:

public bool deleteAllReferences(object obj)
{
allReferences = getAllReferences(obj);
foreach(reference in allReferences)
{
deleteReference(reference);
}
retrun true;
}

The GarbageCollector should have this knowledge, but how can I use it?

Thank you very much for your help

Stefan
 
P

Peter Duniho

Stefan said:
Hello,

i want to delete ALL references of one object. So, i first want to get all
references of one object and then delete them(the refernces).
[...]
The GarbageCollector should have this knowledge, but how can I use it?

You don't.

The GC doesn't really have that knowledge per se. When it does a
collection, it has to scan the entire state of the currently allocated
memory. It does this by starting with the "root" object references
(e.g. static and local variables), and then inspecting each object
references in those for references to other managed objects, traversing
the allocation tree down into those children objects recursively (with
some performance optimizations, of course).

AFAIK, there's no way using just managed code for your own code to
inspect the stack in that way. Even getting access to all the static
variables would involve some tedious reflection.

However, fortunately the actual answer to your question is "don't do
that". If you have a program design in .NET in which you feel you need
to find and set to null all references of a specific object, then your
program design is deeply flawed. The whole point of GC is that you
don't have to deal with explicitly freeing memory, and a program that
does explicitly free managed memory in that way is deeply flawed.

Just design your code so that if a particular object is done with a
particular reference, it either sets that reference to null itself, or
the object itself becomes no longer referenced (and frankly, the latter
is much more common...it should be relatively rare in the code to set
references to null).

Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top