Mario Vernari
Mario Vernari

Reputation: 7304

Why the unreferenced object is not collected by GC?

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.

Upvotes: 3

Views: 377

Answers (2)

Daniel Imms
Daniel Imms

Reputation: 50149

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

GC.Collect();
GC.WaitForPendingFinalizers();

Upvotes: 1

TalentTuner
TalentTuner

Reputation: 17556

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.

Upvotes: 1

Related Questions