Events

  • Thread starter Thread starter Duncan Mole
  • Start date Start date
D

Duncan Mole

Hi,

Can somebody explain to me how and when Event Handling delegates are removed
from the Event delegate. Is it when the instance of the object whose method
it wraps is CG'ed?

Thanks
 
No -- if fact, a delegate essentially holds a reference to the instance (if
applicable), thus the instance won't be GC'ed so long as the delegate is
registered with the event handler. You should remove the event handler
explicitly if it no longer needs to receive event notifications, e.g.

myTextbox.TextChanged -= myEventHandler;

Ken
 
Hi
I believe Not necessary . Delegates are object by themselves. GC work as
follows , it goes to a generation , collect objects that are not referenced
any more then move the remaining part to the next generation . Therefore,
it really depend on the sequence by which the GC pass the objects. It way
pass a delegate find it still in use then collect the object that use the
delegate , this way the delegate would survive this collection may be to
the next one .
Mohamed Mahfouz
MEA Developer Support Center
ITworx on behalf of Microsoft EMEA GTSC
 
hmm, I am sure I am being dumb here but either as Ken suggests the delegate
is effectively a reference to the suscribed object, or, if the object is
GC'ed when subscribed to an event the event may throw a null reference
exception??

This is really nagging me. I know neither of these sceanarios is true. In
the former case we would have memory probems and I am fairly sure the latter
is preposertous too. I just wana know how it works!
 
Sorry you're unconvinced. Here are a couple of people who discuss the issue
of delegates holding strong references to their underlying objects:

http://www.interact-sw.co.uk/iangblog/2004/07/07/circulareventrefs
http://weblogs.asp.net/greg_schechter/archive/2004/05/27/143605.aspx

It's really not that surprising -- if I hold a delegate to an object's
method then I am indirectly holding a reference to the object (since it must
continue to live in order for the method to be invoked). And since an event
is really just a collection of delegates, having a delegate registered as an
event handler keeps the object alive. However, if the event delegate is the
only remaining strong reference to the object, then the object will be
eligible for GC once the object that contains the event is no longer
referenced.

Ken
 
Hi Ken,

I am convinced, I just need it spelling out.
However, if the event delegate is the
only remaining strong reference to the object, then the object will be
eligible for GC once the object that contains the event is no longer
referenced.

Thats the bit I was after!

Thanks for your time

;-)
 
Back
Top