Figures
Figure 4 Allocating and Managing Resources
class Application {
    public static int Main(String[] args) {

      // ArrayList object created in heap, myArray is now a root
      ArrayList myArray = new ArrayList();

      // Create 10000 objects in the heap
      for (int x = 0; x < 10000; x++) {
         myArray.Add(new Object());    // Object object created in heap
      }

      // Right now, myArray is a root (on the thread's stack). So, 
      // myArray is reachable and the 10000 objects it points to are also 
      // reachable.
      Console.WriteLine(a.Length);

      // After the last reference to myArray in the code, myArray is not 
      // a root.
      // Note that the method doesn't have to return, the JIT compiler 
      // knows
      // to make myArray not a root after the last reference to it in the 
      // code.

      // Since myArray is not a root, all 10001 objects are not reachable
      // and are considered garbage.  However, the objects are not 
      // collected until a GC is performed.
   }
}
Figure 8 FileStream's Type Implementation
public class FileStream : Stream {

    public override void Close() {
        // Clean up this object: flush data and close file 
•••
        // There is no reason to Finalize this object now
        GC.SuppressFinalize(this);
    }

    protected override void Finalize() {
        Close();    // Clean up this object: flush data and close file
    }

    // Rest of FileStream methods go here
•••
}
Figure 9 ReRegisterForFinalize and SuppressFinalize
void method() {
    // The MyObj type has a Finalize method defined for it
    // Creating a MyObj places a reference to obj on the finalization table.
    MyObj obj = new MyObj(); 

    // Append another 2 references for obj onto the finalization table.
    GC.ReRegisterForFinalize(obj);
    GC.ReRegisterForFinalize(obj);

    // There are now 3 references to obj on the finalization table.

    // Have the system ignore the first call to this object's Finalize 
    // method.
    GC.SuppressFinalize(obj);

    // Have the system ignore the first call to this object's Finalize 
    // method.
    GC.SuppressFinalize(obj);   // In effect, this line does absolutely 
                                // nothing!

    obj = null;   // Remove the strong reference to the object.

    // Force the GC to collect the object.
    GC.Collect();

    // The first call to obj's Finalize method will be discarded but
    // two calls to Finalize are still performed.
}
Page view tracker