I am trying to understand C# garbage collection and want to simulate a memory leak by using static root field. GC doesn't perform very well (which is good), however the objects are collected. In the example below, why does memory not leak? Should field Counter not prevent instances of MemLeakRoot class from being collected?
This is what is supposed to be a leaking class:
public class MemLeakRoot
{
public static int Counter;
public List<byte[]> MyList;
public MemLeakRoot() { }
public void Do()
{
MyList = new List<byte[]>();
for (int i = 0; i < 10000; i++)
{
MyList.Add(new byte[1024]);
}
Counter++;
}
}
And this is the simulation:
static void Main(string[] args)
{
while (true)
{
var obj = new MemLeakRoot();
obj.Do();
if (MemLeakRoot.Counter != 0 && MemLeakRoot.Counter % 1000 == 0)
{
Console.Write("+");
if (MemLeakRoot.Counter % 100000 == 0) Console.WriteLine(MemLeakRoot.Counter.ToString());
}
}
}