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

前端之家收集整理的这篇文章主要介绍了c# – 在静态字段中引用自身的类是否可以进行垃圾回收?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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

猜你在找的C#相关文章