Garbage collector test

I wrote a simple .net application to test some .NET behavior about how it handles memory along with the garbage collector for cleaning.

The graphical interface of form applications is as follows:

Application GUI

And code like this:

public partial class Form1 : Form
{
    private readonly IList<byte[]> _btyList = new List<byte[]>();

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        int i = 0;

        while (i < 3)
        {
            byte[] buffer = File.ReadAllBytes(@"C:\PFiles\20131018_nl_metro holland.pdf");
            _btyList.Add(buffer);
            i++;
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        int i = 0;

        while (i < _btyList.Count)
        {
            _btyList[i] = null;
            i++;
        }
    }

    private void button3_Click(object sender, EventArgs e)
    {
        GC.Collect();
    }
}

When I add a pair of byte arrays to a private list of byte arrays, it (of course) affects memory usage in the application:

Memory usage after adding byte arrays

Now, when I click the "Clear memory" button, the memory usage will remain unchanged. I can wait several hours, but this does not change. If I click the "Garbage collection" button (after "Clear memory"), it will immediately free the memory:

Memory usage after garbage collect

Question: why the garbage collector does not work in this case?

+4
4

, . , .

4 , 360 , , .

, GC , .

Ref.:

.NET

, : :

  • .

  • , , . .

  • GC.Collect. , . .

+4

, CLR , , . "" .

: - , .

+3

. Garbage collector run is indeterministic, , .

GC , , .

MSDN -

, , . , . . , . , . , , .

+2

The GC starts when a trigger occurs . The trigger may be a failed allocation or a low memory event generated by Windows.

Setting a variable to null is not tracked in any way and is not non .

Your case is a valid use case GC.Collect because you have knowledge about your release patterns that the GC does not have.

+2
source

All Articles