# Monday, 31 December 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, 31 December 2007 22:18:31 (W. Europe Standard Time, UTC+01:00)  #    Comments [1]
Tuesday, 01 January 2008 14:41:45 (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.
Name
E-mail
Home page

I apologize for the lameness of this, but the comment spam was driving me nuts. In order to be able to post a comment, you need to answer a simple question. Hopefully this question is easy enough not to annoy serious commenters, but hard enough to keep the spammers away.

Anti-Spam Question: What method on java.lang.System returns an object's original hashcode (i.e. the one that would be returned by java.lang.Object.hashCode() if it wasn't overridden)? (case is significant)

Answer:  
Comment (HTML not allowed)  

Live Comment Preview