Guido Kraus
11/15/2002 7:22:00 PM
I have a question regarding the lifetime of objects that
listen to events. Consider the following two classes:
'-----------------
Public Class C1
Public Event TestEvent()
Public Sub New()
Dim myC2 As New C2()
myC2.Test(Me)
End Sub
End Class
Public Class C2
Public Sub Test(ByVal myC1 As C1)
AddHandler myC1.TestEvent, _
AddressOf TestEventHandler
End Sub
Public Sub TestEventHandler()
End Sub
End Class
'-----------------
If you instantiate an object of class C1 a temporary
instance of class C2 is created. However, due to the
AddHandler statement, the instance of C2 is not destroyed
after the constructor of C1 returns. As long as the
instance of class C1 is alive, the instance of C2 lives,
too. The only possibility to destroy the C2 instance (and
not destroying the C1 instance) that I'm aware of is
unregistering from the event (via RemoveHandler
statement). As the temporary instance of C2 is not
reachable from my code, I would consider it garbage. The
GC does not.
Is this intended behavior?
I have a major headache because of this. In my project
there are many objects which are interested in events and
therefore have Addhandler statements. However, these
objects are never destroyed even if I remove all
references to them.
Any ideas how to solve this without adding RemoveHandler
statements?
Thanks,
Guido
--
guido.kraus(at)lango.de