Beispiel #1
0
        private static void Example2()
        {
            // first we allocate some objects. the second object we create
            // depends on the first. the second object is going to hook onto
            // the event exposed by the first object.
            Console.WriteLine("Creating instances...");
            var objectWithEvent      = new ObjectWithEvent();
            var objectThatHooksEvent = new HookWithAnonymousDelegate(objectWithEvent);

            // we'll set the instance to null and call the GC, and since we
            // our event handler we've set up doesn't have any dependencies on
            // the object we've hooked with, it will get cleaned up.
            Console.WriteLine();
            Console.WriteLine("Setting the object that hooks the event to null and calling garbage collector...");
            objectThatHooksEvent = null;
            GC.Collect();

            // the first object should be just as easy to get rid of!
            Console.WriteLine("Look at that! Press enter and I'll set the object with the event to null and call the garbage collector one last time.");
            Console.ReadLine();
            objectWithEvent = null;
            GC.Collect();

            Console.WriteLine("And presto! Both are gone.");
        }
Beispiel #2
0
        private static void Example2()
        {
            // first we allocate some objects. the second object we create 
            // depends on the first. the second object is going to hook onto
            // the event exposed by the first object.
            Console.WriteLine("Creating instances...");
            var objectWithEvent = new ObjectWithEvent();
            var objectThatHooksEvent = new HookWithAnonymousDelegate(objectWithEvent);

            // we'll set the instance to null and call the GC, and since we 
            // our event handler we've set up doesn't have any dependencies on
            // the object we've hooked with, it will get cleaned up.
            Console.WriteLine();
            Console.WriteLine("Setting the object that hooks the event to null and calling garbage collector...");
            objectThatHooksEvent = null;
            GC.Collect();

            // the first object should be just as easy to get rid of!
            Console.WriteLine("Look at that! Press enter and I'll set the object with the event to null and call the garbage collector one last time.");
            Console.ReadLine();
            objectWithEvent = null;
            GC.Collect();

            Console.WriteLine("And presto! Both are gone.");
        }