home *** CD-ROM | disk | FTP | other *** search
/ PC Pro 2005 June (DVD) / DPPRO0605DVD.iso / dotNETSDK / SETUP.EXE / netfxsd1.cab / FL_DefiningCleanup_cs________.3643236F_FC70_11D3_A536_0090278A1BB8 < prev    next >
Encoding:
Text File  |  2001-08-21  |  2.0 KB  |  66 lines

  1. using System;
  2.  
  3. // If the base class does not implement IDisposable then
  4. // you should implement the IDisposable interface
  5. // if you want to be cleaned up with C#'s "using" statement
  6. class MyType : IDisposable {
  7.  
  8.    // Called when not explicitly Disposed
  9.    ~MyType() {
  10.       Console.WriteLine("Executing Finalize()");
  11.       Dispose(false);
  12.    }
  13.  
  14.    // Because this is a method on an interface it is
  15.    // automatically virtual.
  16.    public void Dispose() {
  17.       Console.WriteLine("Executing Dispose()");
  18.  
  19.       // Essentially, this sets a flag.
  20.       // If set, then GC will not call Finalize (and thus not Dispose(false))
  21.       // If NOT set, then GC will free the state by calling Finalize(false)
  22.       GC.SuppressFinalize(this);
  23.  
  24.       Dispose(true);
  25.    }
  26.  
  27.    // 1. If flagged, dispose of managed objects
  28.    // 2. Always cleans up *un*managed objects
  29.    // 3. When necessary, clean up base objects with MyBase.Dispose
  30.    protected void Dispose(bool disposing) {
  31.       Console.WriteLine("Executing Dispose(" + disposing.ToString() + ")");
  32.       if (disposing) { // "true" when we have managed objects to clean up
  33.           // Dispose of our own managed objects
  34.           Console.WriteLine("Dispose: This is where we cleanup managed objects");
  35.       }
  36.  
  37.       // Dispose of our own *un*managed object
  38.       Console.WriteLine("Dispose: This is where we cleanup *un*managed objects");
  39.  
  40.       // If you have a base class that defines Dispose(bool), call it
  41.       // base.Dispose(disposing);
  42.  
  43.    }
  44.  
  45.    // Typically used for objects that may be re-opened 
  46.    public void Close() {
  47.       Console.WriteLine("Executing Close()");
  48.       this.Dispose();
  49.    }
  50.  
  51.    public void DoSomething() {
  52.       Console.WriteLine("MyType object is doing something.");
  53.    }
  54. }
  55.  
  56. class App {
  57.    public static void Main() {
  58.       Console.WriteLine("Executing App.Main()");
  59.       using (MyType mt = new MyType()) {
  60.          mt.DoSomething();
  61.       }
  62.  
  63.       Console.Write("Press Enter to terminate application...");
  64.       Console.Read();
  65.    }
  66. }