[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

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

1 Answer

(Gang Guo [MS])

12/10/2002 10:15:00 AM

0

When you add an event handler in C2 for C1's event, actually a delegate is
created in C1which is used to call the event handler in C2. When the
delegate references instance methods, the delegate stores not only a
reference to the method's entry point, but also a reference to the object
instance for which to invoke the method. That's why you need remove the
event handler so that C2 will be garbage collected.

Regards,
Gang Guo
This posting is provided "AS IS" with no warranties, and confers no rights.
Got .Net? http://www.got...