GC and event handlers question

C

Chris DiPierro

Let's say I do the following:

Object A lives "forever" and periodically creates instances of Object B.

Object B triggers events, that Object A registers for immediately upon
the creation of Object B.

Object B is later dereferenced.

Do my handlers to the now dereferences Object B ever get garbage
collected? Or should I explicitly unregister for the events before I
dereference Object B?
 
J

Jon Skeet [C# MVP]

Chris DiPierro said:
Let's say I do the following:

Object A lives "forever" and periodically creates instances of Object B.

Object B triggers events, that Object A registers for immediately upon
the creation of Object B.

Object B is later dereferenced.

Do my handlers to the now dereferences Object B ever get garbage
collected? Or should I explicitly unregister for the events before I
dereference Object B?

That depends really on what you mean by the second part. If you mean:

a.SomeEvent += new EventHandler (b.SomeMethod);

then you need to remove that delegate from the event before b can be
garbage collected.

If you mean:

b.SomeEvent += new EventHandler (a.SomeMethod);

then you don't need to do anything.

Basically, the event has a reference to the target of the delegate, but
not the other way round.
 
C

Chris DiPierro

If you mean:
b.SomeEvent += new EventHandler (a.SomeMethod);

Yes, this is what I meant.
then you don't need to do anything.

Basically, the event has a reference to the target of the delegate, but
not the other way round.

Ok, that's what I thought, but I saw some indication to the contrary in
something I was reading.

Thanks for the help.
 

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