Fog Creek Software
Discussion Board




Welcome! and rules

Joel on Software

Question on delegate references

So, let's say I have:

public class A {
  public event FooEventHandler Fooing;
    ....
}

in another class:

A a = new A();
a.Fooing += new FooEventHandler(MyFooHandler);

now, in all the texts and examples I've read, people never seem to unregister their event handlers.  Is this bad practice?  or does the CLR just take care of it?  If we don't unregister our event handlers, is a reference to 'this' kept in A.Fooing ?  Or is a weak reference, allowing our class that uses A.Fooing to be GC'd ?

And if we do:

a.Fooing -= new FooEventHandler(MyFooHandler), would that work based on the 'equality' of this new instance of FooEventHandler, or does it have to be the same reference of FooEventHandler that was originally +='d to A.Fooing ?

Thanks!

All Foo'd Out.
Monday, January 26, 2004

This them there line of code:

"a.Fooing -= new FooEventHandler(MyFooHandler)"

would work just fine, it's not necessary to preserve the original event handler object as long as you wrap the same method of the same class and instance (unless it's a static method).

As for your other question, I don't really know. I would suppose that keeping an instance event handler registered does keep the object in memory indefinitely; however, it's possible that .NET automatically unregisters event handlers when the object that hosts the event is destroyed.

Chris Nahr
Monday, January 26, 2004

"NET automatically unregisters event handlers when the object that hosts the event is destroyed. "

Correct - it's just another object reference -- it'll get garbage collected when the object to which it's attached (or "higher up") goes out of scope.

Duncan Smart
Monday, January 26, 2004

Ok, but does a registered event handler prevent the referenced object from being GCed?

Alex
Friday, January 30, 2004

"Ok, but does a registered event handler prevent the referenced object from being GCed?"

In these terms: The referencing object holds a delegate to the referenced object. Yes, the possession of that delegate prevents the referenced object from being GC'd, because it is in essence an object reference (albeit an indirect one).

Brad Wilson (dotnetguy.techieswithcats.com)
Sunday, February 01, 2004

*  Recent Topics

*  Fog Creek Home