加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在静态字段中引用自身的类是否可以进行垃圾回收?

发布时间:2020-12-15 08:24:44 所属栏目:百科 来源:网络整理
导读:public class MyClass { private static MyClass heldInstance; public MyClass() { heldInstance = this; }} 假设MyClass的一个实例没有以任何其他方式生根,那么这里的私有静态引用是否会阻止它被垃圾收集? 解决方法 您发布的课程不会被垃圾收集.你可以通
public class MyClass {
  private static MyClass heldInstance;

  public MyClass() {
    heldInstance = this;
  }
}

假设MyClass的一个实例没有以任何其他方式生根,那么这里的私有静态引用是否会阻止它被垃圾收集?

解决方法

您发布的课程不会被垃圾收集.你可以通过给它一个带控制台输出的终结器来测试它:
public class MyClass
{
    private static MyClass heldInstance;
    public MyClass()
    {
        heldInstance = this;
    }
    ~MyClass()
    {
        Console.WriteLine("Finalizer called");
    }
}
class Program
{
    static void Main(string[] args)
    {
        var x = new MyClass(); // object created

        x = null; // object may be eliglible for garbage collection now

        // theoretically,a GC could happen here,but probably not,with this little memory used
        System.Threading.Thread.Sleep(5000);

        // so we force a GC. Now all eligible objects will definitely be collected
        GC.Collect(2,GCCollectionMode.Forced);

        //however their finalizers will execute in a separate thread,so we wait for them to finish
        GC.WaitForPendingFinalizers();

        System.Threading.Thread.Sleep(5000);
        Console.WriteLine("END");

    }
}

输出将是:

END
Finalizer called

这意味着该类仅在应用程序的最终拆解时收集,而不是在常规垃圾收集期间收集.

如果您创建此类的多个实例,如下所示:

var x = new MyClass();
x = new MyClass();
x = new MyClass();
x = new MyClass();

然后除最近的一个之外的所有将被垃圾收集.

你会得到的

Finalizer called
Finalizer called
Finalizer called
END
Finalizer called

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读