473,654 Members | 3,062 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.Referen ce = test

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

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

GC.Collect()
GC.WaitForPendi ngFinalizers()

MsgBox("Is cleaned up? " & Finalized)

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

MsgBox("Finishe d.")
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 1543
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.goo glegroups.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.Referen ce = test
|
| AddHandler source.Blah, AddressOf target.Blah
| source.Fire()
| MsgBox("Created ")
|
| MsgBox("Is cleaned up? " & Finalized)
| source = Nothing
|
| GC.Collect()
| GC.WaitForPendi ngFinalizers()
|
| MsgBox("Is cleaned up? " & Finalized)
|
| ' Test call to target, it still exists
| target.Blah(Not hing, New EventArgs)
|
| MsgBox("Finishe d.")
| 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.WaitForPendi ngFinalizers()
MsgBox("Is cleaned up? " & Finalized)

MsgBox("Finishe d.")
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
1364
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 event sink is on an object that can come and go, what is the proper way to deal with adding and removing the handler to the event list? Should the event sink make sure to remove itself from the source's event list before all other references to it...
7
2461
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 app though, the usage goes to about 500k, and then grows when maximizing the app and working with DataSet. The DataSet still appears to have all data when mem footprint was many many megs at the end of loading it. Two questions: 1) I'm guessing...
6
3455
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 (http://www.seedindustries.com/blog/x/2004_06_01_archive.html) and Greg Schechter’s Avalon solution. 1) Is there a more general solution in C#? 2) Why are delegates not weakreferences? It would seem a logical decision to make - if the only...
14
3247
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 asynchronously (could be a timer but then we get Thread C) Upon completion of DelegateB, Thread B would like to callback ThreadA using DelegateA but as we all know the call to DelegateA is running in ThreadB. Is
3
1168
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. Interfaces define methods and functions that a class which implements the interface must also contain - so I get the impression that an Interface is like a skeleton of the methods... And a delegate defines the arguments for a function which have to...
3
3417
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 general, all links back towards the root of a tree should be weak refs; this breaks the loops that give reference counting trouble. John Nagle
1
1869
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 class for wrapping an event subscription in a "weak" event handler. Unfortunately, I've been bitten by the restriction that one can't do this: public class Blah<T: WeakReference where T : Delegate
2
1874
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 differences between delegates and the use of pointers to objects, I'm nonetheless a little confused by how similar the syntax used for references to methods is to that used for references to objects. Recently at a few different forums I posted a brief...
0
8815
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8707
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8482
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8593
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6161
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4294
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2714
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1916
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1593
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.