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?
The garbage collector isn't running because it doesn't need to. If memory is not low, there is no need to collect.
If you have 4GB of memory, 360MB is probably below the collection threshold.
You shouldn't, in general, ever worry or think about when the GC runs, unless you are writing time or memory critical code.
Ref.: Fundamentals of Garbage Collection
Understanding Garbage Collection in .NET
Garbage collection occurs when one of the following conditions is true:
The system has low physical memory.
The memory that is used by allocated objects on the managed heap surpasses an acceptable threshold. This threshold is continuously adjusted as the process runs.
The GC.Collect method is called. In almost all cases, you do not have to call this method, because the garbage collector runs continuously. This method is primarily used for unique situations and testing.
Garbage collection is relatively slow and the CLR won't do it every time memory becomes free, only when it needs to. So "freeing" your array doesn't trigger it.
Your experiment has been a complete success: you have learned something about how garbage collection works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With