Type Summary



Type Summary


public enum GCHandleType

    {

    Normal = 2,

    Pinned = 3,

 MS Weak = 0,

 MS WeakTrackResurrection = 1,

    }


Example

using System;

using System.Runtime.InteropServices;



/// <summary>

/// Sample demonstrating the use of the GCHandleType enumeration.

/// Use this enumeration to specify the type of handle allocated by the

/// GCHandle class.

/// </summary>

internal class GCHandleTypeSample

{



    private static void Main()

    {

        DemoClass demo = new DemoClass();

        GCHandle  gch  = 

            GCHandle.Alloc(demo, GCHandleType.WeakTrackResurrection);



        Console.WriteLine(

            "'gch' allocated for 'demo' (GCHandleType.WeakTrackResurrection)");

        // Enable resurrection and run the object's finalizer.

        demo.Resurrectable = true;

        demo = null;

        GC.Collect();

        GC.WaitForPendingFinalizers();

        demo = gch.Target as DemoClass;

        if (demo == null)

        {

            Console.WriteLine("'gch' target lost after resurrection");

        }

        else

        {

            Console.WriteLine("'gch' target retained after resurrection");

        }



        Console.WriteLine();



        gch = GCHandle.Alloc(demo, GCHandleType.Weak);



        Console.WriteLine("'gch' allocated for 'demo' (GCHandleType.Weak)");

        // Enable resurrection and run the object's finalizer.

        demo.Resurrectable = true;

        demo = null;

        GC.Collect();

        GC.WaitForPendingFinalizers();

        demo = gch.Target as DemoClass;



        if (demo == null)

        {

            Console.WriteLine("'gch' target lost after resurrection");

        }

        else

        {

            Console.WriteLine("'gch' target retained after resurrection");

        }



        Console.WriteLine();

        Console.WriteLine();

        Console.WriteLine("Press Enter to continue");

        Console.ReadLine();

    }



}



internal class DemoClass

{

    public bool Resurrectable = false;



    ~DemoClass()

    {

        Console.WriteLine("  Finalizing DemoClass");

        

        if (Resurrectable)

        {

            // Make sure that resurrection is turned off otherwise the object

            // will never be finalized.

            Resurrectable = false;

            Console.WriteLine("  Resurrecting DemoClass");

            GC.ReRegisterForFinalize(this);

        }



    }



}


The output is


'gch' allocated for 'demo' (GCHandleType.WeakTrackResurrection)

  Finalizing DemoClass

  Resurrecting DemoClass

'gch' target retained after resurrection



'gch' allocated for 'demo' (GCHandleType.Weak)

  Finalizing DemoClass

  Resurrecting DemoClass

'gch' target lost after resurrection





Press Enter to continue

  Finalizing DemoClass