I have written a simple .net forms application to test some behaviour of .NET about how it handles memory together with the garbage collector to do the cleaning.
The forms application GUI looks like this:
And the code behind 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 couple of byte arrays to the private list of byte arrays it (of course) has effect on the memory usage of the application:
Now when I press the Clear memory button the memory usage will stay the same. I can wait for hours, but it doesn't change. If I press the Garbage collect button (after Clear memory) it will free the memory immediately:
The question is: Why does the garbage collector not work in this case?