0

I wrote this code:

            dog joe = new dog();
            WeakReference wr = new WeakReference(joe);
            if (wr.IsAlive)
            {
                Console.WriteLine("Yes,first time");
            }
            else
            {
                Console.WriteLine("No,first time");
            }

            GC.Collect();

            if (wr.IsAlive)
            {
                Console.WriteLine("Yes,second time");
            }
            else
            {
                Console.WriteLine("No,second time");
            }

And I expected to have this result: Yes,first time No,second time

but it seems that GC didn't collect my WeakReference's target(joe). and result was: Yes,first time Yes,second time

What is my problem?.. do I misunderstand the WeakReferences?

Think
  • 11
  • 4

1 Answers1

5

Your code is correct. Compile as Release and run without the debugger (Shift+F5) or directly from command prompt. For an explanation see Does garbage collection run during debug?

Community
  • 1
  • 1
xanatos
  • 109,618
  • 12
  • 197
  • 280
  • 2
    Or set joe to null when running in debug. – Ian Ringrose Mar 18 '15 at 10:59
  • @IanRingrose That is the fastest method, but it wouldn't show the ability of the GC to see that a local variable isn't used anymore (and some persons say you shouldn't do it, because you are extending the lifetime of the variable) – xanatos Mar 18 '15 at 11:03