垃圾收集器C#,关于'清除'对象的问题

dam*_*ned 4 c# garbage-collection

我读了一些关于垃圾收集的信息(它是如何工作的等等).我试着理解它是如何运作我的例子,但我认为我有问题.我知道Garbage Collector在以下
情况下运行:内存不足,
你调用GC.Collect().
这是我的代码:

public partial class Form1 : Form
{
    public Testing _d;
    public Boolean _first = false;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (!_first)
        {
            _d = new Testing();
            int test = _d.DoSomething("example");
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        _first = true;
    }

    private void button3_Click(object sender, EventArgs e)
    {
        //if (_first)
        //{
        //    _d = null;
        //}
        GC.Collect();
    }
}

public class Testing
{
    private ASCIIEncoding _ascii;
    private bool _disposed = false;

    public Testing()
    {
        _ascii = new ASCIIEncoding();
    }

    public int DoSomething(string message)
    {
        return _ascii.GetByteCount(message);
    }
}
Run Code Online (Sandbox Code Playgroud)

当我点击button1时,我正在创建新的对象测试._d是对这个新对象的引用.我正在使用JetBrains dotTrace Memory转储内存并看到这个新对象存在.单击button2后,我将boolean _first设置为true,以便_d变得无法访问.此时我想当我运行GC.Collect()GC将从堆栈中"清除"此对象,但我发现它仍然存在.我误解了GC的工作?或者我这样做错了?
它在我设置时工作_d = null;

SLa*_*aks 8

单击Button2不会无法_d访问.

GC仅收集未被root对象引用的对象.
只要您的表单有引用_d,就不会收集它.