Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Garbage Collector C#, question about 'clearing' objects

I read some informations about Garbage Collection (how it's works etc.). I tried understand how it's working doing my examples but I think I have problem. I know Garbage Collector runs when:
is not enough memory,
you call GC.Collect().
This is my code:

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);
    }
}

When I click button1 I'm creating new object Testing. _d is reference to this new object. I'm dumping memory using JetBrains dotTrace Memory and see this new object exists. After click button2 I'm setting boolean _first to true in order to _d became unreachable. At this point I thought when I run GC.Collect() GC will 'clear' this object from stack, but I see it's still exists. I misunderstood about GC work? or I'm doing this wrong?
It's working when I set _d = null;

like image 914
damned Avatar asked Dec 01 '22 08:12

damned


1 Answers

Clicking Button2 does not make _d unreachable.

The GC only collects objects that are not referenced by a rooted object.
As long as your form has a reference to _d, it won't be collected.

like image 119
SLaks Avatar answered Dec 02 '22 20:12

SLaks