开发者

In what situation will the object clear up by GC.Collect()?

开发者 https://www.devze.com 2023-01-15 22:39 出处:网络
I am writting a software in Silverlight with C#. 开发者_如何转开发I know that GC.Collect will collect the Objects and Controls if they are non-referenced, but I am not sure what is meant by non-refer

I am writting a software in Silverlight with C#.

开发者_如何转开发I know that GC.Collect will collect the Objects and Controls if they are non-referenced, but I am not sure what is meant by non-reference.

I know that in Silverlight, I have to remove the Control (say called "Control A") from the Layout, take out all the event handler, then set the object to null, so it doesn't reference the object. Something like:

1) if the "Control A" it contains other Controls: "Control B", "Control C", and they might have subscripted event handler somewhere.

Will the "Control A" still get collected by GC.Collect()? And how about "Control B" "Control C"?

Do I have to actually remove everything that "Control B" and "Control C" that contains and remove "Control B" "Control C" from "Control A" to let them get collected?

2) Say if there is a "Control D" continas a ComboBox, and the ComboBox has a lot ComboxBoxItem.

Do I have to Clear() out all the ComboxBoxItem so those ComboxBoxItem will be collected?

Or when I remove ComboBox from "Control D", will take out ComboxBoxItem too?

I am kind of confused with Delete in C++, since in C++ I can just delete the whole object with everything it contains...


If Control A or any contained controls have events, and some other classes subscribed to these events, this means: Control A (B,C) have reference to another class (subscriber). This doesn't prevent these controls to be collected.

If Control A (B, C) subscribed to some event of class D, this means, class D has reference to A (B, C). This prevents these controls to be collected.

Regaring internal mutual references between control A and its children, GC is smart enough to recognize this and collect all of them.


An object will only be collected if it is not referenced (directly or indirectly) by a root variable that is in scope (either on the stack or static). In other words, if A references B and B references A, they'll both get collected.

From http://msdn.microsoft.com/en-us/library/ee787088.aspx:

The garbage collector uses the following information to determine whether objects are live:

Stack roots. Stack variables provided by the just-in-time (JIT) compiler and stack walker.

Garbage collection handles. Handles that point to managed objects and that can be allocated by user code or by the common language runtime.

Static data. Static objects in application domains that could be referencing other objects. Each application domain keeps track of its static objects.

0

精彩评论

暂无评论...
验证码 换一张
取 消