user929794
user929794

Reputation: 223

.Net. Why Garbage collector doesn't run when I clear a list?

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

Answers (2)

Matt Wilko
Matt Wilko

Reputation: 27322

Conditions that trigger garbage collection:

  • 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.

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

Piotr Perak
Piotr Perak

Reputation: 11088

Because system is not in need of memory. GC works as seldom as possible.

Upvotes: 2

Related Questions