views:

131

answers:

3

Hi,

i read the answer of the question Do event handlers stop garbage collection from occuring?, but what happens when the publisher is the target ?

To be more specific, i am using MVVM design for a WPF app. Model-View classes raise a NotifyPropertyChanged on every change. In some classes, i need to call a method when something is modified.

I would like to do this:

this.PropertyChanged += this.MyHandler;

Will this instances be destroyed by the GC ?

+1  A: 

Yes it will, the GC is intelligent enough to determine circular references and collect the objects involved.

It will even handle it over multiple objects so if objectA is listening to an event on objectB and objectB is listening to an event on objectA provided they are both otherwise unreferenced the GC will figure out that it can collect both of them together.

(Best I can quickly find for a reference is another SO question here)

Martin Harris
+1  A: 

Yes the GC will clean the object up since there is nothing external to the object referencing it.

The GC takes all the references held at root level (static fields, references on each threads stack etc.) and leaps from these to objects that these may reference and then to objects the those objects may reference and so on. As it goes it marks each object as "not to be collected". Once it has munched through them anything not yet marked as "not to be collected" is up for collection.

When you follow that through there is no way for the GC to get to your object from the root and hence it will be collected.

AnthonyWJones
+6  A: 

The GC looks and sees if any references to the object are currently rooted in the application. It is smart enough to handle circular references like the one above.

In addition, it is smart enough to handle the case where you have two objects, A, and B, and:

A.Event += B.Handler; 
B.Event += A.Handler;

If A and B both go out of scope, the GC is smart enough to find and clean both of these objects, even though they subscribe to each other. However, if a separate object (in use) refers to either, it will prevent both from being collected.

This is one of the main advantages to a true GC solution, when compared to reference counting solutions. Reference counting will fail to collect this, but the .NET gc will handle it perfectly.

Reed Copsey