views:

147

answers:

2

Say I have two classes, and neither of them are GUI components. Class A is a short lived object that registers for an event declared by a long lived object B. For example

public A(B b)
{
   b.ChangeEvent += OnChangeEvent;
}

If A never deregisters from B's event, will A never be garbage collected? Does A need a Dispose method just to deregister from B's event?

There is also a related second question. If A and B should both live for the entire execution time of the application, does A need to deregister?

A: 

If B holds a reference to A, A will not get Garbage Collected unless B is also eligible for Garbage Collection.

You shouldn't need a Dispose method for this. Once B has no references pointing to it either, the Garbage Collector will be smart enough to dispose both B and A.

If they are both alive for the life of the application, you don't need to deregister the event.

Kevin
... unless A is eligible for garbage collection too.
Jon Skeet
Like Jon said, what about A?
Sean
@Sean, I had B and A reversed. Once external references are removed from B, A will be disposed as well.
Kevin
+1  A: 

To your first question: Yes. B has a reference to A. That way A will live as long as B. This is a nice way to loose memory in a UI app if you e.g. register with an event like App.OnIdle.

To the second: At the end everything will be killed.

flq