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#项目进行IIS部署过程中报错及其一般解决方案_c#iis执行语句...
微信扫码登录PC端网站应用的案例(C#)_c# 微信扫码登录
原文地址:http://msdn.microsoft.com/en-us/magazine/cc163...
前言 随着近些年微服务的流行,有越来越多的开发者和团队所采...
最近因为比较忙,好久没有写博客了,这篇主要给大家分享一下...
在多核CPU在今天和不久的将来,计算机将拥有更多的内核,Mic...