X hits on this document

914 views

0 shares

0 downloads

0 comments

84 / 396

Chapter ‎18   Unsafe code

~B() { Console.WriteLine("Destruct instance of B"); } }

class Test { static void Main() { B b = new B(new A()); b = null; GC.Collect(); GC.WaitForPendingFinalizers(); } }

creates an instance of class A and an instance of class B. These objects become eligible for garbage collection when the variable b is assigned the value null, since after this time it is impossible for any user-written code to access them. The output could be either

Destruct instance of A Destruct instance of B

or

Destruct instance of B Destruct instance of A

because the language imposes no constraints on the order in which objects are garbage collected.

In subtle cases, the distinction between “eligible for destruction” and “eligible for collection” can be important. For example,

using System;

class A { ~A() { Console.WriteLine("Destruct instance of A"); }

public void F() { Console.WriteLine("A.F"); Test.RefA = this; } }

class B { public A Ref;

~B() { Console.WriteLine("Destruct instance of B"); Ref.F(); } }

class Test { public static A RefA; public static B RefB;

Copyright Microsoft Corporation 1999-2003. All Rights Reserved.71

Document info
Document views914
Page views914
Page last viewedWed Dec 07 09:27:42 UTC 2016
Pages396
Paragraphs9401
Words133190

Comments