Reputation: 223
I add 20 Mb to a list several times so that the application consumes 600MB. However why I clear the list, the memory isn't released.
Here is my code
List<int> data = new List<int>();
const int TwentyMB = 20 * 1024 * 1024;
public MainForm()
{
InitializeComponent();
}
private void AddDataButton_Click(object sender, EventArgs e)
{
for (var i = 0; i < TwentyMB; i++)
{
data.Add(i);
}
}
private void DestroyButton_Click(object sender, EventArgs e)
{
data.Clear();
data.Capacity = 0;
}
Until I call GC.Collect, the memory is released
private void CollectButton_Click(object sender, EventArgs e)
{
GC.Collect();
}
Can anyone tell me why the memory isn't release? When will GC work automatically?
Upvotes: 0
Views: 186
Reputation: 27322
Conditions that trigger garbage collection:
The Garbage collection time can vary depending on the machine it is running on and the resources available. in your case you can see that calling GC.Collect does in fact free up the memory, so there is nothing to worry about. If you wait for a few minutes after you clear the list you will probably see the same thing happening, but as I said this time can vary
Upvotes: 1
Reputation: 11088
Because system is not in need of memory. GC works as seldom as possible.
Upvotes: 2