I am trying to find the reasons for the increase of memory usage over time in my app, specially when a user opens and closes a lot of forms. I am doing some tests trying to understand what are the things that I may be doing wrong, and I found a case I can't understand: if I instantiate a form with a static AutoCompleteStringCollection assigned to a ComboBox, the form finalizer is not called until I close the app. If I remove the static keyword, the finalizer is called in the next click and works as expected.
I was able to reproduce it in an empty project using .NET 6: every time I click the button, the memory keeps growing with every instance of the big Bitmap in Form2 and never gets released. Without the static keyword, only one Bitmap is kept in memory, the last one.
My question is: why a static variable not referenced anywhere else is keeping the instance of the Form2 from beeing collected by the GC?
public class Form1 : Form
{
public Form1()
{
var button = new Button() { Text = "Click Me" };
button.Click += (s, e) =>
{
Form2 dummy = new Form2();
dummy = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
};
this.Controls.Add(button);
}
}
public class Form2 : Form
{
//Remove static keyword for the finalizer to be called
private static AutoCompleteStringCollection SearchText = new AutoCompleteStringCollection();
private Bitmap bigObject = new Bitmap(1000, 10000);
public Form2()
{
var combo = new ComboBox();
combo.AutoCompleteCustomSource = SearchText;
this.Controls.Add(combo);
}
~Form2()
{
//Not being called until I close the app
}
}