c# - 在静态字段中引用自身的类可以被垃圾收集吗?

标签 c# static garbage-collection private

public class MyClass {
  private static MyClass heldInstance;

  public MyClass() {
    heldInstance = this;
  }
}

假设 MyClass 的实例没有以任何其他方式作为根,这里的私有(private)静态引用是否会阻止它被垃圾收集?

最佳答案

您发布的类(class)不会被垃圾回收。您可以通过给它一个带有控制台输出的终结器来测试它:

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# - 在静态字段中引用自身的类可以被垃圾收集吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15099700/

相关文章:

garbage-collection - 什么时候在java中使用垃圾收集器?

java - 符合垃圾收集条件的对象

c# - 如何在 C# 中向 UserControl 添加事件?

c# - ASP.NET Core 和 formdata 与文件和 json 属性绑定(bind)

java - 多个线程将对象引用传递给静态辅助方法

c++ - 如何使用静态对象和方法!? C++ 挫败感

java - protected 静态方法访问

r - 使用 gc() 命令强制在 R 中运行垃圾回收

c# - 如何防止具有公共(public)派生类的抽象类被其他程序集继承?

c# - C# 中的日志文件锁定问题