473,387 Members | 1,859 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Delegates appear to be weak references

Hi,

I've heard from groups that listeners to event handlers cause
references to be kept alive, if the targets are marked to stay alive. I
need to make sure that attaching events to objects will not cause them
to be kept open.

I created a test which has "target" listening to "source" for events.
After plugging source into target, I then let go of source. Since I'm
still holding onto target, if delegates were a strong reference, then
target shouldn't be collected. What I find is that it _is_ being
garbage collected, which is what I want.

If I add a normal reference to source from target, then the garbage
collection does not fire, as I expect.

Am I missing something? Why am I seeing a weak reference behaviour for
event delegates when others seem to witness strong referencing? Is this
an event vs delegate issue? Having tested this behaviour, I am about to
rely upon this in a design.

TIA,

Matthew Herrmann
Far Edge Pty Ltd
http://www.faredge.com.au/

----------------

Public Module Startup

Public Sub Main()
Dim target As New Target

Dim source As Source
source = New Source

'target.Reference = test

AddHandler source.Blah, AddressOf target.Blah
source.Fire()
MsgBox("Created")

MsgBox("Is cleaned up? " & Finalized)
source = Nothing

GC.Collect()
GC.WaitForPendingFinalizers()

MsgBox("Is cleaned up? " & Finalized)

' Test call to target, it still exists
target.Blah(Nothing, New EventArgs)

MsgBox("Finished.")
End Sub

Public Finalized As Boolean = False
End Module

Friend Class Source
Public Event Blah As EventHandler

Protected Overrides Sub Finalize()
Finalized = True
MyBase.Finalize()
End Sub

Public Sub Fire()
RaiseEvent Blah(Me, New EventArgs)
End Sub
End Class

Friend Class Target
Public Reference As Source

Public Sub Blah(ByVal sender As Object, ByVal e As EventArgs)
MsgBox("Fired!")
End Sub
End Class

Nov 21 '05 #1
2 1533
Matthew,
| Am I missing something?
Yes.

| Why am I seeing a weak reference behaviour for
| event delegates when others seem to witness strong referencing?
You're not seeing weak reference behavior... As much as you are looking at
the wrong object...

| AddHandler source.Blah, AddressOf target.Blah
| source.Fire()
| source = Nothing
The source object is holding a reference to the target object. The target
object has no knowledge or reference to the source object. Hence when you
let go of the source reference the source object is free to be collected.

However! The "problem" that others are talking about is when you let go of
any explicit references to the target object, the source object still has
some implicit references to the target object, preventing the target object
from being collected.
--
Hope this helps
Jay [MVP - Outlook]
..NET Application Architect, Enthusiast, & Evangelist
T.S. Bradley - http://www.tsbradley.net
"Matthew Herrmann" <ma************@faredge.com.au> wrote in message
news:11**********************@g43g2000cwa.googlegr oups.com...
| Hi,
|
| I've heard from groups that listeners to event handlers cause
| references to be kept alive, if the targets are marked to stay alive. I
| need to make sure that attaching events to objects will not cause them
| to be kept open.
|
| I created a test which has "target" listening to "source" for events.
| After plugging source into target, I then let go of source. Since I'm
| still holding onto target, if delegates were a strong reference, then
| target shouldn't be collected. What I find is that it _is_ being
| garbage collected, which is what I want.
|
| If I add a normal reference to source from target, then the garbage
| collection does not fire, as I expect.
|
| Am I missing something? Why am I seeing a weak reference behaviour for
| event delegates when others seem to witness strong referencing? Is this
| an event vs delegate issue? Having tested this behaviour, I am about to
| rely upon this in a design.
|
| TIA,
|
| Matthew Herrmann
| Far Edge Pty Ltd
| http://www.faredge.com.au/
|
| ----------------
|
| Public Module Startup
|
| Public Sub Main()
| Dim target As New Target
|
| Dim source As Source
| source = New Source
|
| 'target.Reference = test
|
| AddHandler source.Blah, AddressOf target.Blah
| source.Fire()
| MsgBox("Created")
|
| MsgBox("Is cleaned up? " & Finalized)
| source = Nothing
|
| GC.Collect()
| GC.WaitForPendingFinalizers()
|
| MsgBox("Is cleaned up? " & Finalized)
|
| ' Test call to target, it still exists
| target.Blah(Nothing, New EventArgs)
|
| MsgBox("Finished.")
| End Sub
|
| Public Finalized As Boolean = False
| End Module
|
| Friend Class Source
| Public Event Blah As EventHandler
|
| Protected Overrides Sub Finalize()
| Finalized = True
| MyBase.Finalize()
| End Sub
|
| Public Sub Fire()
| RaiseEvent Blah(Me, New EventArgs)
| End Sub
| End Class
|
| Friend Class Target
| Public Reference As Source
|
| Public Sub Blah(ByVal sender As Object, ByVal e As EventArgs)
| MsgBox("Fired!")
| End Sub
| End Class
|
Nov 21 '05 #2
Thanks Jay, you're spot on. Source needs to know target, not vice
versa.

I've modified the code to test the condition and sure enough, target
does not get GC'd unless the RemoveHandler is there.

I've posted the updated code for people's future reference.
-- Matthew
--------

Public Module Startup

Public Sub Main()
Dim source As Source
source = New Source

Dim target As Target
target = New Target

AddHandler source.Blah, AddressOf target.Blah
source.Fire()

MsgBox("Created")

MsgBox("Is cleaned up? " & Finalized)

' When the following line is uncommented, target is not
' collected:
' RemoveHandler source.Blah, AddressOf target.Blah
target = Nothing

GC.Collect()
GC.WaitForPendingFinalizers()
MsgBox("Is cleaned up? " & Finalized)

MsgBox("Finished.")
End Sub

Public Finalized As Boolean = False
End Module

Friend Class Source
Public Event Blah As EventHandler

Public Sub Fire()
RaiseEvent Blah(Me, New EventArgs)
End Sub
End Class

Friend Class Target
Protected Overrides Sub Finalize()
Finalized = True
MyBase.Finalize()
End Sub

Public Sub Blah(ByVal sender As Object, ByVal e As EventArgs)
MsgBox("Fired!")
End Sub
End Class

Nov 21 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: BlueMonkMN | last post by:
I've been trying to think of the right way to design relationships between objects with different desired lifetimes that raise events. If an event source is a relatively permanent object and the...
7
by: Derrick | last post by:
I'm loading a boatload of data into a DataSet. The memory usage grows and grows for the app while loading that data. Calling GC.Collect() reduces the consumption slightly. When I minimize the...
6
by: Andrew Hayes | last post by:
Having to remember to unregister for events to prevent a ref count seems to be quite a burden to place on a developer. I have reviewed the WeakMulticastDelegate solution proposed by Xavier Musy...
14
by: Lior Amar | last post by:
Quick question about threads and delegates. I have the following scenario Thread A (CLASSA) spawns Thread B (CLASSB) and passes it a DelegateA to a callback Thread B Invokes a DelegateB...
3
by: Rich | last post by:
Hello, I recently started using delegates in my VB apps to handle asynchronous operations. Based on the examples that I followed, delegates appear to work in a similar way as Interfaces. ...
3
by: John Nagle | last post by:
Are weak refs slower than strong refs? I've been considering making the "parent" links in BeautifulSoup into weak refs, so the trees will release immediately when they're no longer needed. In...
1
by: Bruce Wood | last post by:
I'm trying to "genericize" the following class. At the moment I have derived classes for each different type of event handler / event arguments, and I wanted to have a single, generic, catch-all...
2
by: BobLewiston | last post by:
The concept of delegates (references to methods) per se is new to me (although I used function pointers in C years ago), and although the literature acknowledges that there are significant...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.