Best Practice for removing objects from delegates/events before garbagecollection?

C

CB

When designing an object, is there a best practice for how to allow the
user of the object to tell the object to remove itself from any
delegates / events it has registered with?

For example.. say we have a static settings class, and it has some
OnChange event. The object I am writing will add a method to the
settings OnChange event in its constructor. Obviously, at some point,
the method needs to be removed from the event so the new object can be
garbage collected. Since IDispose is only supposed to be used for
cleaning up unmanaged memory, where should I put the unwire call? [if
this were c++, i would put it in the destructor, but that isn't an
option in C#]

It seems like the only suitable approach is the following. However, I am
curious if there is some standard naming convention for the methods.

{
// in the constructor, listener adds itself to the settings event
Listener listener = new Listener();
...
// use listener
...
listener.Detach();
listener = null;
}

Also, could move the adding of the object to the event from the objects
constructor to some Attach() method the user most call.


Thanks.
 
G

Guest

I would put that in dispose. It is where things like cleaning up data
connections and things go. Things the garbage collector will not do
automatically.
This seems to be something exactly like that to me.

Ciaran O'Donnell
 

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