best practice for deregistering events -= ?

J

Jim

Hi,

I'm working with someone else's code and have an issue with the
application design for registering and de-registering events.


In the existing code...

Events are registered as shown below. If the routine that owns this
code is executed unexpectedly more than once. Then there can be more
than one registration for the event.

blah.blahChanged += new EventHandler(this.blahButton_BlahChanged);

Also, the existing code uses the dispose event to deregister the events
as shown below.

public virtual void Dispose()
{
blah.blah-= new KeyEventHandler(blah);
blah.blah-= new KeyEventHandler(blah);
blah.blah-= new KeyEventHandler(blah);
}

Then the existing code forces a garbage collection using GC.Collect;

Is this a bad thing??? Is it ok to use the dispose method to deregister
events by forcing a garbage collection?

I prefer to use this method...

blah.blahChanged -= new EventHandler(this.blahButton_BlahChanged);
blah.blahChanged += new EventHandler(this.blahButton_BlahChanged);

it ensures that only one registration exists.

I deregister events in other locations. not in the dispose routines?


Comments?
 
G

Guest

Aside from incorrect implementation of the Dispose pattern, you're right, you
shouldn't deregister events in the Dispose method.
 
M

Myron Marston

Alex said:
Aside from incorrect implementation of the Dispose pattern, you're right, you
shouldn't deregister events in the Dispose method.

Maybe I'm misunderstanding you, but Isn't this the proper way to
prevent memory leaks when an object registers for an event but doesn't
own the object it's registering with? For example:

Class A exposes event "ValueChanged".
Object B creates and holds an instance of Class A.
Class C has a property "AInstance" of the type Class A.
Object C (of type Class C) creates and holds Object B.
Object B sets Object C.AInstance = Object A.
At this point, Object C registers with Object A's ValueChanged event.
At some later point, Object C is disposed. Shouldn't it deregister
from Object A's ValueChanged event handler?

Without doing this, Object A would continue to hold a reference to
Object C because Object C has registered an event handler with Object
A. The GC wouldn't collect Object C since something still has a
reference to it. The memory would never be cleaned up until the
application ends.

Or am I missing something here?
 

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