On Wed, 21 May 2008 08:31:01 -0700, Barry Gilbert
<Ba**********@discussions.microsoft.comwrote:
>I have a class that raises events that downstream objects subscribe to. In
one case, after destroying the object, the event seems to still get handled
in a subscriber object. So I instantiate an object and the event fires
correctly. Then I destroy the object and instantiate another instance and the
subscriber event handler get hit twice. I've tried using IDisposible and also
using GC.Collect, but it didn't seem to help. I've also tried using
RemoveHandler before destroying the object.
It's not clear to me whether the handler is firing because the objects are
still in memory or for some other reason.
Any help would be appreciated.
Setting a reference to null does not make an object go away. It just
makes it eligible for garbage collection.
Suppose for example I create an instance of class X. In the
constructor the class creates an instance of a timer and sets the
timer to fire every second.
Immediately after creating the instance I set the reference to it to
null. Until the garbage collector runs and collects this instance,
the timer will continue to fire. The instance is still there, and
until the garbage collector runs and checks things no one knows that
there are no longer any references to the instance.
You say "the subscriber event handler get hit twice". Is that twice
for the same instance, or once for two different instances?
If twice for the same instance, then you have subscribed to the event
twice.
If for two different instances, then you need to find out why the
class that you no longer have references to is still generating
events.
Perhaps you need to implement IDispose in your classes, and have the
Dispose method 'turn off' the class - make it stop doing whatever
generates events. Then if you dispose of the class when you are
finished with it, it will stop generating events.