Groups | Blog | Home
all groups > dotnet performance > september 2007 >

dotnet performance : Releasing Objects in C'# so that GC can reclaim the memory.


Chris Arnold
9/20/2007 12:00:00 AM
Hi All,

I have a number of questions related to making objects available for
collection by the GC. I have an application that is leaking memory to the
point of filling up all 3 heap generations and then throwing
OutOfMemoryException.

Question 1

I class has a property "public IList<SomeClass> MyCollection". In this
class' Dispose(bool) method I am setting this.MyCollection null. Do I need
to remove all the objects from the list before doing this? My worry is that
the items in the list will become 'orphaned' yet still referenced and,
therefore, passed over by the GC.

Question 2

An object will only be 'removed' by the GC if it is no longer referenced by
anything. If I have wired up one of that object's events to an event handler
do I need to remove it first (e.g. myObject.MyEvent -= new
EventHandler(this.eventhandler);) ?

Question 3

I create a new object and wire up its Success event to an event handler
method. I then start this object running on a new thread (using
Thread.Start()). When this event is handled and the object has finished
executing, will it automatically go out of scope? Or, in the event handler
to I have to first unwire the event (again using the -= syntax from Q2)?

Many thanks, in advance.

Chris

Ben Schwehn
9/20/2007 5:54:12 AM
[quoted text, click to view]

no

[quoted text, click to view]

no, an eventhandler does not keep the object alive


[quoted text, click to view]

no same as 2, if the object is not referenced anymore, the handler will
not keep it alive.


You can use WinDbg to find out what objects are filling your heap.

There used to be free profiler that showed you the usage of the heap
without such a steep lerning curve (compared to using windbg), but I
can't seem to find it atm, your search engine of choice might help you.

Henning Krause [MVP - Exchange]
9/20/2007 5:39:55 PM
Hello,

[quoted text, click to view]

this is contrary to my experience (and contrary to
http://diditwith.net/2007/03/23/SolvingTheProblemWithEventsWeakEventHandlers.aspx).

If I have an object A which points to object B via an eventhandler, object B
is not discarded until object A is also collected.

[quoted text, click to view]

A very nice profiler is the one from SciTech (http://memprofiler.com/). They
do have a thirty day trial version.

Kind regards,
Henning Krause
AddThis Social Bookmark Button