473,545 Members | 2,049 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Object garbage collection of events

Object garbage collection of events

I can not help wondering how the garbage collection system handles
events.

If I release all references to an object that has a void that an event
somewhere is using I then have no access to the class holding the void
so it should be garbage collected.

But if an event holds a reference to a void of the class that I have
no reference to douse the class stay in memory because something
refers to it or is that reference removed from the event.

Basically do I need to remove all event calls before releasing an
object or are they removed automatically.

I hope someone understands what I mean.

This code thaw incomplete hopefully helps explain what I mean.

Thank you all

Jay Dee

<code>

static class Program
{
static void Main()
{
Form1 form = new Form1();
form.myClass = new MyClass();
form.MyEvent += new EventHandler(fo rm.myClass.MyEv entCall);
form.myClass = null;
Application.Run (form);
}
}

public class Form1 : System.Windows. Forms.Form
{
MyClass myClass;

public event System.EventHan dler MyEvent;

public void OnMyEvent(Event Args e)
{
if (this.MyEvent != null)
{
this.MyEvent(th is, e);
}
}
}

public class MyClass
{
public void MyEventCall(obj ect sender, EventArgs e)
{
// do somthing.
}
}

</code>
Jul 26 '08 #1
11 2205
Events do not hold refences to objects, nor does garbage collection relate
to an object's events.

An object is elligible for garbage collection when it has no "applicatti on
roots", that is it is no longer reachable from any code paths in the
application. Hooking an object up to an event handler (registering
delegates to handle event notifications for the object) do not count as an
application root. Only object variables count.

-Scott
"Jay Dee" <fi******@gmail .comwrote in message
news:a0******** *************** ***********@m44 g2000hsc.google groups.com...
Object garbage collection of events

I can not help wondering how the garbage collection system handles
events.

If I release all references to an object that has a void that an event
somewhere is using I then have no access to the class holding the void
so it should be garbage collected.

But if an event holds a reference to a void of the class that I have
no reference to douse the class stay in memory because something
refers to it or is that reference removed from the event.

Basically do I need to remove all event calls before releasing an
object or are they removed automatically.

I hope someone understands what I mean.

This code thaw incomplete hopefully helps explain what I mean.

Thank you all

Jay Dee

<code>

static class Program
{
static void Main()
{
Form1 form = new Form1();
form.myClass = new MyClass();
form.MyEvent += new EventHandler(fo rm.myClass.MyEv entCall);
form.myClass = null;
Application.Run (form);
}
}

public class Form1 : System.Windows. Forms.Form
{
MyClass myClass;

public event System.EventHan dler MyEvent;

public void OnMyEvent(Event Args e)
{
if (this.MyEvent != null)
{
this.MyEvent(th is, e);
}
}
}

public class MyClass
{
public void MyEventCall(obj ect sender, EventArgs e)
{
// do somthing.
}
}

</code>

Jul 26 '08 #2
On Fri, 25 Jul 2008 18:50:22 -0700, Jay Dee <fi******@gmail .comwrote:
Object garbage collection of events

I can not help wondering how the garbage collection system handles
events.

If I release all references to an object that has a void that an event
somewhere is using I then have no access to the class holding the void
so it should be garbage collected.
What do you mean by "void"? If you mean a method or delegate, then you're
severely abusing the word "void".
But if an event holds a reference to a void of the class that I have
no reference to douse the class stay in memory because something
refers to it or is that reference removed from the event.

Basically do I need to remove all event calls before releasing an
object or are they removed automatically.
Assuming you are asking whether, in the code you posted, the instance of
MyClass becomes eligible for garbage collection when "form.myCla ss = null"
is executed, the answer is "no", the event handler is not removed
automatically and so the MyClass instance remains reachable.

Pete
Jul 26 '08 #3
On Fri, 25 Jul 2008 20:34:38 -0700, Scott M. <s-***@nospam.nosp amwrote:
Events do not hold refences to objects,
Indirectly, they do.
nor does garbage collection relate to an object's events.
It does. Regardless of what the delegate references, an event retains a
reference to any delegate subscribed to the event. If that delegate was
constructed from an instance method, then it includes a reference to the
class instance used, and so the event implicitly also includes that
reference.
An object is elligible for garbage collection when it has no
"applicatti on
roots", that is it is no longer reachable from any code paths in the
application. Hooking an object up to an event handler (registering
delegates to handle event notifications for the object) do not count as
an
application root. Only object variables count.
There's no difference between an event and any other field in the object.
None are actually "roots", as the class instance must be referenced by
something else (for example, by a local variable on the stack, which
_would_ be a root), but as long as the object itself is reachable, so too
is anything referenced by its fields, including any events.

Pete
Jul 26 '08 #4
Do this in an MdiChild form
MdiParent.Activ ated += SomeMethod;

Then dispose of that MdiChild form. The form will not be collected until
the main form closes.

Pete

Jul 26 '08 #5
On Jul 25, 9:07*pm, "Peter Duniho" <NpOeStPe...@nn owslpianmk.com>
wrote:

I wonder: how do you manually collect a static object/variable?
Specifically, a static class. In another thread I created a static
class for a subform/child window that works fine but 'hangs around',
and when the subform/child window is reopened, the static class is
still there, and creates problems since it's part of an Event/Delegate
model.

RL
Jul 26 '08 #6
raylopez99 wrote:
On Jul 25, 9:07 pm, "Peter Duniho" <NpOeStPe...@nn owslpianmk.com>
wrote:

I wonder: how do you manually collect a static object/variable?
Specifically, a static class. In another thread I created a static
class for a subform/child window that works fine but 'hangs around',
and when the subform/child window is reopened, the static class is
still there, and creates problems since it's part of an Event/Delegate
model.

RL
The object isn't static, it's only the reference to the object that is
static. The object is allocated on the heap just like any other object,
and if you remove the reference from the static variable (e.g. setting
it to null), the object can be garbage collected.

--
Göran Andersson
_____
http://www.guffa.com
Jul 26 '08 #7
On Jul 25, 11:34*pm, "Scott M." <s-...@nospam.nosp amwrote:
Events do not hold refences to objects, nor does garbage collection relate
to an object's events.

An object is elligible for garbage collection when it has no "applicatti on
roots", that is it is no longer reachable from any code paths in the
application. *Hooking an object up to an event handler (registering
delegates to handle event notifications for the object) do not count as an
application root. *Only object variables count.

-Scott
This misunderstandin g could be costly...

http://www.codeproject.com/KB/showca...SProfiler.aspx
Jul 26 '08 #8
I thank you all for your valuable responses.

Sorry for miss using the word “void” I think that I mean “method”.

I am still slightly confused as there seems to be two different views
here and I don’t know witch is correct.

Would I be correct in saying that in my example above a call to
“form.MyEvent” will not call the method “MyEventCall” as I no longer
have a valid reference to that method.

Or is that method still valid because the event its self still refers
to it.

Thank you all.

Jay Dee
Jul 26 '08 #9
On Sat, 26 Jul 2008 10:05:11 -0700, Jay Dee <fi******@gmail .comwrote:
[...]
Would I be correct in saying that in my example above a call to
“form.MyEvent ” will not call the method “MyEventCallâ €ť as I no longer
have a valid reference to that method.
No, that would be incorrect.
Or is that method still valid because the event its self still refers
to it.
Yes. When you subscribe to the event, a delegate is created ("new
EventHandler(.. .)"), and that delegate references the instance of MyClass
used to create the delegate. As long as the event itself is reachable, so
too will be anything it references, and anything that it references
references, and so on.

Just because _some_ reference to that instance of MyClass no longer
exists, that doesn't make the instance go away. It's only when that
instance of MyClass becomes "unreachabl e" that the instance may be garbage
collected. An instance is "reachable" if a reference to it is stored in a
root (such as a static field or local variable), or a reference to it is
stored in a data structure that is itself "reachable" (so there's a
recursive aspect to the definition of "reachable" , as noted above).

So in your example, as long as the Form1 instance is reachable, so too is
any class instance referenced in a delegate subscribed to an even in the
Form1 instance.

Basically: the garbage collector doesn't go around invalidating
references. Instead, it collects objects only when you can no longer get
at them.

Pete
Jul 26 '08 #10

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

Similar topics

1
5988
by: Egghead | last post by:
Hi all, I'm just wondering that is any way to dispose all objects when my app is shut down? I mean I can use for.. next loop to unload all loaded form when I shut down my app. Thank you, Egghead
7
2660
by: cmrchs | last post by:
Hi, how do you mark an object for garbage collection in C++.NET 2005 ? MyDbClass^ obj = gcnew MyDbClass(); // Release the object obj = 0; --> COMPILER ERROR obj = nullptr; // nope : this does not mark it for garbage // collection (see help)
9
1188
by: Rob Nicholson | last post by:
Is it possible to trap the creation of a new object and carry out other operations after it's been created? For example, if creating an object of a specific type, then add a reference to a global collection. Thanks, Rob.
2
3188
by: bughunter | last post by:
This is partly 'for the record' and partly a query about whether the following is a bug somewhere in .Net (whether it be the CLR, JITter, C# compiler). This is all in the context of .Net 1.1 SP1. Recently we (my fellow team members & I) observed an InvalidOperationException - 'collection has been modified', however it wasn't immediately...
9
2185
by: Olivier Fermy | last post by:
I have created a sample project where i have referenced an object only with an event : textBox.VisibleChanged += new EventHandler(this.textBox_VisibleChanged); When i call GC.Collect(), the object is disposed and garbage collected ! I thought that event references are strong references and not weak references. Does the .NET 2.0 garbage...
5
2503
by: Michael Moreno | last post by:
Hello, In a class I have this code: public object Obj; If Obj is a COM object I would like to call in the Dispose() method the following code: System.Runtime.InteropServices.Marshal.ReleaseComObject(Obj);
16
2878
by: anonymous.user0 | last post by:
The way I understand it, if I have an object Listener that has registered as a listener for some event Event that's produced by an object Emitter, as long as Emitter is still allocated Listener will stay alive. Is this correct? If this is correct, I've got a problem. Let's say I've got an object Customer that has an PurchaseList...
13
4501
by: | last post by:
Hi all, Coming from the good old VB6 days we were told to always destroy our objects as follows:- Dim obj as New MyObject ' do some work with obj obj = Nothing I have been doing this in .Net also for quite a while now. The other day one
3
1553
by: =?Utf-8?B?QmFycnkgR2lsYmVydA==?= | last post by:
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...
0
7468
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7401
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7656
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. ...
0
7808
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...
0
5972
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5329
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...
0
4945
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3450
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3443
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.