Form GC question

C

cronusf

Say you have one reference to a form, and that form has child
controls.

myForm = new MyForm();

Then you set myForm to null so that it is garbage collected:

myForm = null;

Is myForm really garbage collected? Because, don't its child controls
have references to myForm since they keep track of their parents? How
does the form get flagged for GC without having to iterate over all of
its children and manually removing them from the form?
 
P

Pavel Minaev

Say you have one reference to a form, and that form has child
controls.

myForm = new MyForm();

Then you set myForm to null so that it is garbage collected:

myForm = null;

Is myForm really garbage collected?

At that specific moment, no. But it will eventually
 Because, don't its child controls
have references to myForm since they keep track of their parents?  How
does the form get flagged for GC without having to iterate over all of
its children and manually removing them from the form?

..NET garbage collector is not reference-counting, it's tracing. That
means that it will detect groups of objects that, while potentially
referencing themselves, have no outside references to them. Once it
does that, it will free those objects (calling finalizers as needed,
etc). This means that you do not have to worry about reference cycles,
but this also means that garbage collection is non-deterministic
(because tracing the object graph after every reference change is
prohibitively expensive, so it does it periodically on a separate
thread).

For more information, including descriptions of some common
implementation techniques (if you're interested), see here:

http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)#Tracing_garbage_collectors
 
P

Phil Wilson

Last time I looked you were supposed to call Form.Dispose() because it
enumerates its controls and calls Dispose on them too. At the risk of
stating the obvious, these contain unmanaged resources (and Finalizers for
people who forget to call Dispose() )

If you're in Debug mode all bets are off because Debug mode generally uses
scope for deciding when to deallocate objects.
 
P

Phil Wilson

Understood, but I took the OP's question to be more like "how do I clean up
a form", and in that context Form.Dispose() is a better solution than
setting it to null, yes? ShowDialog () is common, so I suspect the OP is
using it too.
 

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