问题描述
在 C# 中,当没有对它的引用时,对象会被垃圾回收.假设是这种情况,是否会收集以下任何一种,或者垃圾收集器是否足够聪明,可以同时丢弃它们?
In c#, an object is subject to garbage collection when there are no references to it. Assuming that is the case, would either of the following ever be collected or is the garbage collector smart enough to discard them both?
class Program
{
static void Main()
{
A a = new A();
a.b = new B();
a.b.a = a;
a = null;
}
{
class A
{
public B b;
}
class B
{
public A a;
}
推荐答案
一旦不再需要它们,它们都将有资格获得收集.这意味着在某些情况下,甚至可以在定义对象的范围结束之前收集对象.另一方面,实际收集也可能发生得更晚.
They will both become eligible for collection as soon as they are not needed anymore. This means that under some circumstances, objects can be collected even before the end of the scope in which they were defined. On the other hand, the actual collection might also happen much later.
.NET 垃圾收集器不是基于引用计数的,因此循环依赖没有区别.
.NET garbage collector is not based on reference counting, so cyclic dependency makes no difference.
它基于 mark-and-sweep 算法,该算法将所有对象视为收集的候选对象,然后从可用的根(局部变量、静态变量)遍历对象图,将它们标记为仍然活动".那些没有被标记为仍在使用的,被收集起来.请注意,这有点简化描述:.NET中真正的算法是采用mark-and-sweep,托管堆分为3代+大对象堆,finalization完全忽略等等.
It is based on mark-and-sweep algorithm, which treats all objects as candidates for collection and then traverses the object graph from the available roots (local variables, static variables), marking them as still 'alive'. Those that don't get marked as still being in use, get collected. Please note that this is a bit simplified description: the real algorithm in .NET is adapted mark-and-sweep, managed heap is divided into 3 generations + large object heap, finalization is completely ignored, etc.
我建议查看 Maoni Stephens 的博客 了解更多信息.
I suggest checking Maoni Stephens' blog for more information.
这篇关于什么时候对象会被垃圾回收?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!