Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

Here's my situation, I have a collection of objects which have collections of objects several levels deep. When I am done working with these objects I call .Clear() method on the topmost object. MSDN2 states that this method will clear the collection and release object members for garbage collection. Does this mean that it's recursive and child collections will also be released or will the subsequent children still be alive and kicking in memory?

 

In pseudocode it would look someething like this (assume all members are exposed correctly):

 

[csharp]

class A

{

Collection<B> _b;

}

class B

{

Collection<C> _c;

}

class C

{

somevar = 1;

}

 

main

{

Collection<A> collA = new Collection<A>();

//load collection and its children, do processing

 

//time to unload

collA.Clear();

}

[/csharp]

 

Would that work fine or do I need to go through each child collection manually clearing it?

 

[csharp]

main

{

Collection<A> collA = new Collection<A>();

//load collection and its children, do processing

 

//time to unload

collA.B.C.Clear();

collA.B.Clear();

collA.Clear();

}

[/csharp]

 

My concern are the dangling objects which won't be picked up by the garbage collector until far far later.

  • Leaders
Posted
The garbage collection works by reference tracing. It starts with "roots" (for example, a UI element, namely a form, would be a root since the user can interact with it and raise events or trigger function calls), and traces all the references. Any isolated objects (objects that do not have any delegates or references pointing to them, and therefore can not possibly interact with any other code or UI) or isolated groups of objects are collected. When you release an entire collection, as long as nothing else (that can be traced to from a root) has a reference to the items in the collection, they are available for garbage collection.
[sIGPIC]e[/sIGPIC]
Posted
Would it help to explicitely destroy (or at least dereference by setting to null) large child objects of the collection to facilitate faster memory reclamation or is it just a waste of time and code?

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...