Csharp/C Sharp/Development Class/Garbage Collection — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Текущая версия на 11:43, 26 мая 2010

Check the Generation for an object array

 
using System;
using System.Collections.Generic;
using System.Text;
public class Car {
    private int currSp;
    private string petName;
    public Car() { }
    public Car(string name, int speed) {
        petName = name;
        currSp = speed;
    }
    public override string ToString() {
        return string.Format("{0} is going {1} MPH",
            petName, currSp);
    }
}
class Program {
    static void Main(string[] args) {
        Car refToMyCar = new Car("Zippy", 100);
        Console.WriteLine(refToMyCar.ToString());
        Console.WriteLine(GC.GetGeneration(refToMyCar));
        object[] tonsOfObjects = new object[50000];
        for (int i = 0; i < 50000; i++)
            tonsOfObjects[i] = new object();
        GC.Collect(0);
        GC.WaitForPendingFinalizers();
        Console.WriteLine(GC.GetGeneration(refToMyCar));
    }
    public static void MakeACar() {
        Car myCar = new Car();
    }
}


Demonstrates forced garbage collection

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
//
// gc.cs -- Demonstrates forced garbage collection
//
//          Compile this program with the following command line:
//              C:>csc gc.cs
//
namespace nsGarbage
{
    using System;
    using System.Threading;
    
    public class GCDemo
    {
        static public void Main ()
        {
            long Mem = GC.GetTotalMemory (false);
            Console.WriteLine ("Beginning allocated memory is " + Mem);
            for (int x = 0; x < 10000; ++x)
            {
                clsClass howdy = new clsClass();
            }
            Mem = GC.GetTotalMemory (false);
            Console.WriteLine ("Allocated memory before garbage collection is " + Mem);
            GC.Collect ();
            Mem = GC.GetTotalMemory (true);
            Console.WriteLine ("Allocated memory after garbage collection is " + Mem);
        }
    }
    class clsClass
    {
        public clsClass () { }
        public int x = 42;
        public float f = 2E10f;
        public double d = 3.14159;
        public string str = "This here"s a string";
    }
}


demonstrates forced garbage collection 1

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example21_14.cs demonstrates forced garbage collection
*/
using System;
class Junk
{
  public Junk()
  {
    Console.WriteLine("Created Junk");
  }
  ~Junk()
  {
    Console.WriteLine("Destroyed Junk");
  }
}
public class Example21_14 
{
  public static void Main() 
  {
    Console.WriteLine("Starting Main");
    // create a Junk object
    Junk j = new Junk();
    
    // and destroy it
    j = null;
    // force a garbage collection
    GC.Collect();
    Console.WriteLine("Exiting Main");
  }
}


Estimated bytes on heap

 
using System;
using System.Collections.Generic;
using System.Text;
class Program {
    static void Main(string[] args) {
        Console.WriteLine("Estimated bytes on heap: {0}", GC.GetTotalMemory(false));
        Console.WriteLine("This OS has {0} object generations.\n", (GC.MaxGeneration + 1));
    }
}


Finalizable Disposable Class with using

 
using System;
using System.Collections.Generic;
using System.Text;

public class MyResourceWrapper : IDisposable {
    public void Dispose() {
        Console.WriteLine("In Dispose() method!");
    }
}
class Program {
    static void Main(string[] args) {
        MyResourceWrapper rw = new MyResourceWrapper();
        if (rw is IDisposable)
            rw.Dispose();
        using (MyResourceWrapper rw2 = new MyResourceWrapper()) {
        }
    }
}


Get Total Memory

 
using System;

public class MyClass {
    public void Dispose() {
        Console.WriteLine("Dispose()");
        GC.SuppressFinalize(this);
    }
}
public class ReRegFinalApp {
    public static void DoSomething() {
        MyClass t = new MyClass();
        Console.WriteLine(t);
        t.Dispose();
        GC.ReRegisterForFinalize(t);
    }
    public static void Main(string[] args) {
        long n = GC.GetTotalMemory(true);
        Console.WriteLine("start of Main: {0} bytes allocated", n);
        DoSomething();
        n = GC.GetTotalMemory(true);
        Console.WriteLine("end of Main: {0} bytes allocated", n);
    }
}


IDisposable interface

using System;
namespace Client.Chapter_5___Building_Your_Own_Classes
{
      public class DTOR: IDisposable
      {
           public static int[] MyIntArray;
           private static int ObjectCount = 0;
           private bool Disposed = false;
           static void Main(string[] args)
           {
                 MyIntArray = new int[10];
                  ObjectCount++;
             }
            //Used to clean up and free unmanaged resources
            //Never mark this class as virtual as you do not want derived 
            //classes to be able to override it.
            public void Dispose()
            {
                  //if this class is derived then call the base
                  //class dispose.
                  //base.Dispose();
                  //Call the overloaded version of dispose
                  Dispose(true);
                  //Tell the CLR not to run the finalizer this way
                  //you do not free unmanaged resources twice
                  GC.SuppressFinalize(this);
                 
            }
            //If user calls dispose both managed and unmanaged resources
            //are freed
            //If the finalizer is called then only unmanaged resources are freed
            private void Dispose(bool disposing)
            {
                  if(!this.Disposed)
                  {
                         if(disposing)
                         {
                              //free any managed resources
                         }
  
                         //free unmanaged resources
                  }
                  
                  Disposed = true;
            }
            //This finalizer method is called by the GC,
            //not the user. The net result of having this is that
            //the object will always survive the first GC cycle and
            //will be collected the next time GC1 is collected.
            ~DTOR()
            {
                  Dispose(false);
            }
      }
}


If object array is still alive

 
using System;
using System.Collections.Generic;
using System.Text;
public class Car {
    private int currSp;
    private string petName;
    public Car() { }
    public Car(string name, int speed) {
        petName = name;
        currSp = speed;
    }
    public override string ToString() {
        return string.Format("{0} is going {1} MPH",
            petName, currSp);
    }
}
class Program {
    static void Main(string[] args) {
        Car refToMyCar = new Car("Zippy", 100);
        Console.WriteLine(refToMyCar.ToString());
        Console.WriteLine("\nGeneration of refToMyCar is: {0}", GC.GetGeneration(refToMyCar));
        object[] tonsOfObjects = new object[50000];
        for (int i = 0; i < 50000; i++)
            tonsOfObjects[i] = new object();
        GC.Collect(0);
        GC.WaitForPendingFinalizers();
        Console.WriteLine("Generation of refToMyCar is: {0}",GC.GetGeneration(refToMyCar));
        if (tonsOfObjects[9000] != null) {
            Console.WriteLine("Generation of tonsOfObjects[9000] is: {0}",GC.GetGeneration(tonsOfObjects[9000]));
        } else
            Console.WriteLine("tonsOfObjects[9000] is no longer alive.");
    }
    public static void MakeACar() {
        Car myCar = new Car();
    }
}


MaxGeneration is zero based.

 
using System;
using System.Collections.Generic;
using System.Text;
public class Car {
    private int currSp;
    private string petName;
    public Car() { }
    public Car(string name, int speed) {
        petName = name;
        currSp = speed;
    }
    public override string ToString() {
        return string.Format("{0} is going {1} MPH",
            petName, currSp);
    }
}
class Program {
    static void Main(string[] args) {
        Console.WriteLine("Estimated bytes on heap: {0}", GC.GetTotalMemory(false));
        Console.WriteLine("This OS has {0} object generations.\n", (GC.MaxGeneration + 1));
        Car refToMyCar = new Car("Zippy", 100);
        Console.WriteLine(refToMyCar.ToString());
        Console.WriteLine("\nGeneration of refToMyCar is: {0}", GC.GetGeneration(refToMyCar));
    }
    public static void MakeACar() {
        Car myCar = new Car();
    }
}


Print out how many times a generation has been swept.

 
using System;
using System.Collections.Generic;
using System.Text;
public class Car {
    private int currSp;
    private string petName;
    public Car() { }
    public Car(string name, int speed) {
        petName = name;
        currSp = speed;
    }
    public override string ToString() {
        return string.Format("{0} is going {1} MPH",petName, currSp);
    }
}
class Program {
    static void Main(string[] args) {
        Car refToMyCar = new Car("A", 100);
        Console.WriteLine(refToMyCar.ToString());
        Console.WriteLine(GC.GetGeneration(refToMyCar));
        object[] tonsOfObjects = new object[50000];
        for (int i = 0; i < 50000; i++)
            tonsOfObjects[i] = new object();
        GC.Collect(0);
        GC.WaitForPendingFinalizers();
        Console.WriteLine("Generation of refToMyCar is: {0}",GC.GetGeneration(refToMyCar));
        if (tonsOfObjects[9000] != null) {
            Console.WriteLine("Generation of tonsOfObjects[9000] is: {0}",GC.GetGeneration(tonsOfObjects[9000]));
        } else
            Console.WriteLine("tonsOfObjects[9000] is no longer alive.");
        Console.WriteLine("\nGen 0 has been swept {0} times", GC.CollectionCount(0));
        Console.WriteLine("Gen 1 has been swept {0} times", GC.CollectionCount(1));
        Console.WriteLine("Gen 2 has been swept {0} times", GC.CollectionCount(2));
    }
    public static void MakeACar() {
        Car myCar = new Car();
    }
}


System.IDisposable interface and ensure fastest cleaning up as possible after an object

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example8_9.cs illustrates the use of the
  the System.IDisposable interface and the using statement
  to ensure fastest cleaning up as possible after an object
*/
using System;
// declare the Car class
class Car : System.IDisposable
{
  // declare a field
  public string make;
  // implement the Dispose() method
  public void Dispose()
  {
    Console.WriteLine("In Dispose()");
    // do any cleaning up here
    // stop the garbage collector from cleaning up twice
    GC.SuppressFinalize(this);
  }
  // override the Finalize() method
  ~Car()
  {
    Console.WriteLine("In Finalize()");
    // call the Dispose() method
    Dispose();
  }
}

public class Example8_9
{
  public static void Main()
  {
    // create a Car object within the using statement
    using (Car myCar = new Car())
    {
      // the Car object (and object reference) are only
      // available within this block
      myCar.make = "Toyota";
      System.Console.WriteLine("myCar.make = " + myCar.make);
    }
    System.Console.WriteLine("At the end of Main()");
  }
}