Dispose and Finalize methods

Here are are few tips on using the IDisposable pattern and using Finalizers

  • Implement IDiposable if accessing managed resources like SQLConnection/Command objects and not disposing them from within the method which instantiates the managed resource
  • Implement Finalizer only if using unmanaged resources (Files, Streams, Windows Handles, Pinvoke) and not disposing them from with the method that instantiates the unmanaged resources
  • Insure that each Type that has a finalizer is responsible for disposing only 1 unmanaged resource, and never reference “reference types” from within a Finalizer
  • Use a protected “disposed” bool within a IDiposable type and check its value in the beginning of each method of that type
  • If a type has a “Open” method which opens a managed resource, then insure that you Implement a Close() method which calls the explicit implementation of IDisposable.Dispose() method
   1: public class EncryptedStream : IDisposable
   2: {
   3:     public void Close()
   4:     {
   5:         (this as IDisposable).Dispose();
   6:     }
   7:  
   8:     void IDisposable.Dispose()
   9:     {
  10:        //Release resources
  11:     }
  12: }

  • If the Dispose() method can be called from multiple threads then insure that you use lock(this) before releasing resources. Here is a correct implementation of IDisposable and Finalize pattern which has unmanaged and managed resources to release:
   1: public class DisposeType : IDisposable
   2: {
   3:     protected bool disposed;
   4:     //insure the access modifier is protected so that derived classes can also make use of the same    
   5:     protected virtual void Dispose(bool disposing)
   6:     {
   7:         if (disposed)
   8:             return;
   9:  
  10:         lock (this)
  11:         {
  12:             if (disposing)
  13:             {
  14:                 // Release Managed resources here
  15:             }
  16:             // Release UnManaged resources here
  17:             //call the base object's Dispose protected method
  18:             base.Dispose(disposing);
  19:             disposed = true;
  20:         }
  21:     }
  22:  
  23:     public void Dispose()
  24:     {
  25:         Dispose(true);
  26:         GC.SuppressFinalize(this);
  27:     }
  28:  
  29:     ~DisposeType()
  30:     {
  31:         Dispose(false);
  32:     }
  33: }
  • Compound Finalizable objects: If you have a finalizable object that occupies lot of memory then consider splitting it into 2 classes, one that contains the finalizable object and other that contains the high memory using variables:
   1: public class CompoundObject : IDisposable
   2: {
   3:     //this array takes lot of memory
   4:     int[] array;
   5:     //instance of inner finalizable object
   6:     ClipBoardWrapper cwrapper;
   7:  
   8:     public CompoundObject(int hwnd, int elements)
   9:     {
  10:         array = new int[elements];
  11:         cwrapper = new ClipBoardWrapper(hwnd);
  12:     }
  13:  
  14:     public void Dispose()
  15:     {
  16:         cwrapper.Dispose();
  17:     }
  18:  
  19:     private class ClipBoardWrapper : IDisposable
  20:     {
  21:         [System.Runtime.InteropServices.DllImport("user32")]
  22:         private static extern int OpenClipboard(int hwnd);
  23:  
  24:         [System.Runtime.InteropServices.DllImport("user32")]
  25:         private static extern int CloseClipboard();
  26:         
  27:         public ClipBoardWrapper(int hwnd)
  28:         {
  29:             OpenClipboard(hwnd);
  30:         }
  31:         
  32:         public void Dispose()
  33:         {
  34:             CloseClipboard();
  35:             GC.SuppressFinalize(this);
  36:         }
  37:         ~ClipBoardWrapper()
  38:         {
  39:             Dispose();
  40:         }
  41:  
  42:     }
  43: }

Print | posted @ Friday, March 06, 2009 1:04 PM

Comments on this entry:

Gravatar # re: Dispose and Finalize methods
by Tim at 3/9/2009 2:15 AM

Locking on 'this' is discouraged in the framework design guidelines, see http://blogs.msdn.com/brada/archive/2003/11/12/50664.aspx

Gravatar # http://canada.goodnano-av.com/
by pedapneug at 8/10/2009 8:28 PM

Best reviews of the day about Canada, Canada culture, Personal loan canada and Govrnment jobs canada http://canada.goodnano-av.com/
Gravatar # http://automoto.goodnano-av.com/
by objessesendip at 8/31/2009 10:21 PM

Questions and answers about 1973 oldsmobile 442 and Intrigue oldsmobile recall.
Gravatar # http://clothes.goodnano-av.com/
by Musskarosek at 9/14/2009 10:31 AM

Adidas soccer boots and Tecnica moon boots, Kids rubber boots and Frey boots here http://clothes.goodnano-av.com/
Gravatar # http://college.goodnano-av.com/
by Dantmultynono at 9/15/2009 2:05 PM

Looking for List of college degrees? Labette community college is here! http://college.goodnano-av.com/
Gravatar # http://computers.goodnano-av.com/
by Seewfoucoum at 9/17/2009 5:47 AM

Computer brands and What are computer virus, New computer softwares and Background computer here http://computers.goodnano-av.com/
Gravatar # http://county.goodnano-av.com/
by Heicedotwed at 10/2/2009 7:05 AM

Most recent information about County historical map missouri stone topographical and Paulding county here http://county.goodnano-av.com/
Gravatar # http://cumshot.goodnano-av.com/
by envigegoWex at 10/9/2009 7:24 AM

Best choice of the month: Cumshot, Longest cumshot, Cumshot video and Cumshot clips here http://cumshot.goodnano-av.com/
Gravatar # http://deals.goodnano-av.com/
by FoownClossy at 10/12/2009 11:08 AM

By the way, Deal news, Late deal on holidays events, Big deal reviews and Deal to vegas tips still available http://deals.goodnano-av.com/
Gravatar # http://dildo.goodnano-av.com/
by Kistitybali at 10/14/2009 8:21 PM

Only for you daily news, events and tips about Dildo and Dildo contortionist http://dildo.goodnano-av.com/
Gravatar # http://download.goodnano-av.com/
by StertyUnlitle at 10/16/2009 12:56 PM

aiting for NEWS? Welcome! See about Download, Kazaalite free download, Download free softwear, Download media player free http://download.goodnano-av.com/
Gravatar # Your most actual Moulinex resources!
by BaisaLekSkibe at 10/30/2009 2:37 PM

Best reviews of the day: Lexicon, Arabic lexicon, 2 dictionary lexicon quotation shakespeare vol and Greek english lexicon http://electronics.goodnano-av.com/
Gravatar # http://fantasy.goodnano-av.com/
by agofeglenuece at 11/4/2009 10:21 AM

As about Fantasy, Draft fantasy nfl, Advance fantasy final tactic, Final fantasy 3 walkthrough http://fantasy.goodnano-av.com/
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
Twitter