3

Maybe it's me, but I'm wondering about this (strange) behavior.

Consider the below snippet, which is the minimum Console program to illustrate the effect.

class MyClass { }

class Program
{
    static void Main(string[] args)
    {
            var x = new MyClass();
            var y = new MyClass();

            x = null;
            GC.Collect();

            Console.ReadKey();
    }
}

When the program halts for a keypress (or also by placing a breakpoint), the memory profiler shows that there are two "MyClass" instances still referenced.

The GC.Collect() does not help, nor running the program as "Release".

Shouldn't the unreferenced MyClass instance be collected as soon, at least by forcing the GC collection?

NOTE: the larger Console app involves a bunch of threads producing data, and the MyClass-like instance act as consumers. The instances are referenced via WeakReference, but it seems that's not an issue. The problem is that I am not able to trash a consumer by running all my test lifecycle in the Main method.

Thanks in advance.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Mario Vernari
  • 6,649
  • 1
  • 32
  • 44
  • Have you tried to use `GC.WaitForFullGCComplete();`? GC may run asynchronously in non-blocking mode – Ilya Ivanov Mar 22 '13 at 11:27
  • And `GC.WaitForPendingFinalizers()` – Matthew Watson Mar 22 '13 at 11:28
  • For you all, I tried many GC pattern, including the suggested Collect-WaitForPendingFinalizers-Collect, but without any result. I'd love if anyone could try the same, because I'm seriously thinking to some problem on my platform... – Mario Vernari Mar 22 '13 at 11:34

2 Answers2

1

GC.Collect(); does not guaranteed to be completed immediately , it starts a background thread and returns immediately so the moment profiler checks it , it may be not collected.

TalentTuner
  • 17,262
  • 5
  • 38
  • 63
1

GC.Collect() runs asynchronously. In order to run it synchronously you need to call:

GC.Collect();
GC.WaitForPendingFinalizers();
Community
  • 1
  • 1
Daniel Imms
  • 47,944
  • 19
  • 150
  • 166