Event handlers and finalize

S

Scott Meddows

I'm adding event handlers for dynamically loaded assemblies into a program. I know that I must unregister those event handlers so
the GC can pick up the objects, should I do this in the finalize method?

Thanks.
 
C

CJ Taylor

RemoveHandler


Scott Meddows said:
I'm adding event handlers for dynamically loaded assemblies into a
program. I know that I must unregister those event handlers so
 
S

Scott Meddows

yeah, I got the syntax down. I was just wondering if the finalize method would be the best place to do this...
 
C

CJ Taylor

Sorry... I apologize for the weak response. Yeah, I do some of my stuff in
the finalizer. Just don't depend on anything else with it. That is, you
don't know exactly when the finalizer is going to be called.

-CJ
 
S

Scott Meddows

I'm okay with that. It's just unwiring the event handlers so it can get cleaned up properly.

Thanks for the help!
 
J

Jay B. Harlow [MVP - Outlook]

Scott,
the GC can pick up the objects, should I do this in the finalize method?
No!

Three reasons:

First: Think about it, if the Finalize method is being called, then the GC
must have "picked up" the object.

Second: If the finalize method is being called on the object handling the
event, then the object offering the event may also be finalizable & already
finalized. In other words the object you are attempting to remove or remove
from may not exist!

Third: Finalize is to be used for unmanaged resources (Win32 file/GDI
handles), adding a Finalize method to classes can hurt performance, as those
objects will survive at least 2 collections of the garbage collector (adding
memory pressure).

Normally the object that called AddHandler is the object that I use to call
RemoveHandler as that is the object the "owns" the handler itself. For
example in a collection of objects that want to handle the events of
contained objects, I call AddHander in the collections Add method &
RemoveHandler in the Remove method. I may then have this collection
implement the IDisposable pattern & the Dispose method to remove all the
objects & their handlers, especially if the collection can go away without
having the objects go away.

Hope this helps
Jay



Scott Meddows said:
I'm adding event handlers for dynamically loaded assemblies into a
program. I know that I must unregister those event handlers so
 

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