问题
There are two scenario that i trying to understand how will GC will act
1- There is two object - object1 and object2 object1 has reference on object2 and object2 has reference on object1 Now, both of those object are not in use and GC can collect them.
What will happened ? does GC skip on this collection ? ?
2- Same question but we have 4 ( or n ) objects that have reference on each other. What GC will do on this case ???
回答1:
The GC used by .NET is a tracing garbage collector ("Mark and Sweep" is a related term)
Memory objects are considered "garbage" if they can no longer be reached by following pointers/references from the non-garbage part of your program's memory.
To determine what is reachable and what is not, the GC first establishes a set of root references/pointers. Those are references that are guaranteed to be reachable. Examples include local variables and static fields.
It then follows these references recursively (traces) and marks each object it encounters as "not garbage". Once it runs out of references to follow, it enters the "sweep" phase where every object that has not been marked as "non garbage" is freed (which might include invoking the object's finalizer).
So as soon as none of the objects in your "object ring" is referenced by any part of your "live" objects, it will be garbage collected.
回答2:
Unlike COM, the common language runtime does not use reference counting to govern object lifetime. Instead, the garbage collector traces object references and identifies objects that can no longer be accessed by running code.
This simplifies component programming a great deal, because you do not have to worry about circular references. If a group of objects contain references to each other, but none of these object are referenced directly or indirectly from stack or shared variables, then garbage collection will automatically reclaim the memory.
http://msdn.microsoft.com/en-us/library/0t81zye4(v=vs.71).aspx
回答3:
AFAIK, the GC will only collect objects which no longer have any references to them. So as long as some object has a reference to it, it won't be collected.
If the objects exist for long enough, they will end up in the next phase of the collection cycle.
回答4:
i'm not sure but you could just try it by creating massive amounts of objects (4 threads,filling lists) and then nulling the lists. if the ram goes down,it knows that there is no reference to the block of referenced objects anymore,if it doesn't it doesn't :)
回答5:
Duplicate of Does the CLR garbage collection methodology mean it's safe to throw circular object references around?. .NET's GC isn't a reference counter, it goes over all allocated objects and attempts to link them to a GC root object. It can handle and dispose these circular references, no matter how many of them there are.
来源:https://stackoverflow.com/questions/9176260/what-will-garbage-collector-will-do-in-this-case