# Monday, December 31, 2007
« Argh! | Main | New Development Snapshot »
Argh! Part 2
using System;
using
System.Runtime.InteropServices;

class
Program
{
    GCHandle handle;

    Program()
    {
        handle = GCHandle.Alloc(this, GCHandleType.WeakTrackResurrection);
    }

    ~Program()
    {
        Console.WriteLine(handle.Target != null);
    }

    static void Main()
    {
        new Program();
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}
 

Judging from the comments, many people had trouble understanding the previous code snippet. The above code is equivalent (except that this actually works on .NET 2.0). Maybe this will help clarify.

Monday, December 31, 2007 10:18:31 PM (W. Europe Standard Time, UTC+01:00)  #    Comments [1]
Tuesday, January 1, 2008 2:41:45 PM (W. Europe Standard Time, UTC+01:00)
As I understand it the GCHandle is intended to be used outside the CLR and the WeakReference inside it. My guess is that the GC made an optimization when treating a WeakReference wish is in turn only referenced by the object been finalized ignoring the process all together because this WR isn't going to be useful any way.
Comments are closed.