当一个对象被垃圾收集? [英] When is an object subject to garbage collection?

查看:155
本文介绍了当一个对象被垃圾收集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,当有任何未被引用的对象受垃圾收集。假如是这样的话,将以下任一曾经收集或垃圾收集足够聪明,放弃他们两个?



 类节目
{
静态无效的主要()
{
A A =新的A();
A·B =新的B();
a.b.a =一;
A = NULL;
}

{

等级A
{
公众B B;
}

类B
{
公开发行A一;
}


解决方案

它们都将成为资格收集只要它们不再需要。这意味着,在某些情况下,对象可以甚至在它们被限定的范围的端部之前收集。另一方面,实际的收集也可能会发生更晚



.NET垃圾收集器不是基于引用计数,所以循环依赖没什么区别。



它是基于马克 - 清除的算法,它把所有对象为集合的候选人,然后遍历从可用根对象图(局部变量,静态变量),将其标记为还活着。那些没有得到标记为仍在使用之中,得到收集。请注意,这是一个有点简单说明:在.NET中真正的算法适用标记和清除,托管堆分为3代+大对象堆,终止被完全忽略,等等



我建议检查猫腻斯蒂芬斯'博客了解详情。


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 garbage collector is not based on reference counting, so cyclic dependency makes no difference.

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.

I suggest checking Maoni Stephens' blog for more information.

这篇关于当一个对象被垃圾收集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆