Export (0) Print
Expand All

IDisposable Interface

Defines a method to release allocated unmanaged resources.

For a list of all members of this type, see IDisposable Members.

[Visual Basic]
Public Interface IDisposable
[C#]
public interface IDisposable
[C++]
public __gc __interface IDisposable
[JScript]
public interface IDisposable

Classes that Implement IDisposable

Class Description
AsymmetricAlgorithm Represents the abstract base class from which all implementations of asymmetric algorithms must inherit.
BinaryReader Reads primitive data types as binary values in a specific encoding.
BinaryWriter Writes primitive types in binary to a stream and supports writing strings in a specific encoding.
Brush Classes derived from this abstract base class define objects used to fill the interiors of graphical shapes such as rectangles, ellipses, pies, polygons, and paths.
CacheDependency Tracks cache dependencies, which can be files, directories, or keys to other objects in your application's Cache. This class cannot be inherited.
Component Provides the base implementation for the IComponent interface and enables object-sharing between applications.
ComponentDesigner Base designer class for extending the design mode behavior of a component.
Container Encapsulates zero or more components.
Control Defines the properties, methods, and events that are shared by all ASP.NET server controls.
CryptoAPITransform Performs a cryptographic transformation of data.
Cursor Represents the image used to paint the mouse pointer.
CustomLineCap Encapsulates a custom user-defined line cap.
DesignerTransaction Provides a way to group a series of design-time actions to improve performance and enable most types of changes to be undone.
EncoderParameter You can use an EncoderParameter object to pass an array of values to an image encoder. You can also use an EncoderParameter object to receive a list of possible values supported by a particular parameter of a particular image encoder.
EncoderParameters Encapsulates an array of EncoderParameter objects.
EventHandlerList Provides a simple list of delegates. This class cannot be inherited.
Font Defines a particular format for text, including font face, size, and style attributes. This class cannot be inherited.
FontCollection Base class for installed and private font collections. Provides a method to get a list of the font families contained in the collection. For additional information on fonts and text, including example code, see Fonts and Text in the Using GDI+ Managed Classes section of these documents.
FontFamily Defines a group of type faces having a similar basic design and certain variations in styles. This class cannot be inherited.
FromBase64Transform Converts a CryptoStream from base 64.
Graphics Encapsulates a GDI+ drawing surface. This class cannot be inherited.
GraphicsPath Represents a series of connected lines and curves. This class cannot be inherited.
GraphicsPathIterator Provides the ability to iterate through subpaths in a GraphicsPath object and test the types of shapes contained in each subpath. This class cannot be inherited.
HashAlgorithm Represents the base class from which all implementations of cryptographic hash algorithms must derive.
HttpApplication Defines the methods, properties, and events common to all application objects within an ASP.NET application. This class is the base class for applications defined by the user in the global.asax file.
Icon Represents a Windows icon, which is a small bitmap image used to represent an object. Icons can be thought of as transparent bitmaps, although their size is determined by the system.
Image An abstract base class that provides functionality for the Bitmap and Metafile descended classes.
ImageAttributes An ImageAttributes object contains information about how bitmap and metafile colors are manipulated during rendering. An ImageAttributes object maintains several color-adjustment settings, including color-adjustment matrices, grayscale-adjustment matrices, gamma-correction values, color-map tables, and color-threshold values.

During rendering colors can be corrected, darkened, lightened, removed, and so on. To apply such manipulations, initialize an ImageAttributes object and pass the address of that ImageAttributes object (along with the address of an Image object) to the DrawImage method.

IsolatedStorageFile Represents an isolated storage area containing files and directories.
License Provides the abstract (MustInherit in Visual Basic) base class for all licenses. A license is granted to a specific instance of a component.
LocalizationExtenderProvider Provides design-time support for localization features to a root designer.
ManagementObjectCollection Represents different collections of management objects retrieved through WMI. The objects in this collection are of ManagementBaseObject-derived types, including ManagementObject and ManagementClass.

The collection can be the result of a WMI query executed through a ManagementObjectSearcher object, or an enumeration of management objects of a specified type retrieved through a ManagementClass representing that type. In addition, this can be a collection of management objects related in a specified way to a specific management object - in this case the collection would be retrieved through a method such as GetRelated.

The collection can be walked using the ManagementObjectCollection.ManagementObjectEnumerator and objects in it can be inspected or manipulated for various management tasks.

ManagementObjectCollection.ManagementObjectEnumerator Represents the enumerator on the collection.
MarshalByValueComponent Implements IComponent and provides the base implementation for remotable components that are marshaled by value (a copy of the serialized object is passed).
Matrix Encapsulates a 3-by-3 affine matrix that represents a geometric transform. This class cannot be inherited.
MessageEnumerator Provides a forward-only cursor to enumerate through messages in a message queue.
MessageQueueEnumerator Provides a forward-only cursor to enumerate through messages in a message queue.
MessageQueueTransaction Provides a Message Queuing internal transaction.
OdbcDataReader Provides a way of reading a forward-only stream of data rows from a data source. This class cannot be inherited.
OdbcTransaction Represents an SQL transaction to be made at a data source. This class cannot be inherited.
OleDbDataReader Provides a way of reading a forward-only stream of data rows from a data source. This class cannot be inherited.
OleDbTransaction Represents an SQL transaction to be made at a data source. This class cannot be inherited.
OracleDataReader Provides a way of reading a forward-only stream of data rows from a data source. This class cannot be inherited.
OracleTransaction Represents a transaction to be made at a database. This class cannot be inherited.
PaintEventArgs Provides data for the Paint event.
Pen Defines an object used to draw lines and curves. This class cannot be inherited.
Region Describes the interior of a graphics shape composed of rectangles and paths. This class cannot be inherited.
RegistryKey Represents a key level node in the Windows registry. This class is a registry encapsulation.
ResourceReader Enumerates .resources files and streams, reading sequential resource name and value pairs.
ResourceSet Stores all the resources localized for one particular culture, ignoring all other cultures, including any fallback rules.
ResourceWriter Writes resources in the system-default format to an output file or an output stream.
ResXResourceReader Enumerates XML resource (.resx) files and streams, and reads the sequential resource name and value pairs.
ResXResourceWriter Writes resources in an XML resource (.resx) file or an output stream.
SearchResultCollection Contains the SearchResult instances that the Active Directory hierarchy returned during a DirectorySearcher query.
ServicedComponent Represents the base class of all classes using COM+ services.
Socket Implements the Berkeley sockets interface.
SqlCeCommand Represents an SQL statement to execute against a data source.
SqlCeConnection Represents an open connection to a data source.
SqlCeDataReader Provides a way of reading a forward-only stream of data rows from a data source. This class cannot be inherited.
SqlCeEngine Represents the properties, methods, and other objects of the SQL Server CE Engine. This class cannot be inherited.
SqlCeRemoteDataAccess Initializes a new instance of the SqlCeRemoteDataAccess object. For more information about Remote Data Access, see the SQL Server CE Books Online.
SqlCeReplication Initializes a new instance of the SqlCeReplication object. For more information on replication, see SQL Server Books Online. For more information on merge replication in SQL Server CE, see the SQL Server CE Books Online.
SqlCeTransaction Represents an SQL transaction to be made at a data source. This class cannot be inherited.
SqlDataReader Provides a means of reading a forward-only stream of rows from a SQL Server database. This class cannot be inherited.
SqlTransaction Represents a Transact-SQL transaction to be made in a SQL Server database. This class cannot be inherited.
Stream Provides a generic view of a sequence of bytes.
StringFormat Encapsulates text layout information (such as alignment and line spacing), display manipulations (such as ellipsis insertion and national digit substitution) and OpenType features. This class cannot be inherited.
SymmetricAlgorithm Represents the abstract base class from which all implementations of symmetric algorithms must inherit.
TcpClient Provides client connections for TCP network services.
TempFileCollection Represents a collection of temporary files.
TemplateEditingVerb Represents a designer verb that creates a template editing frame, and can only be invoked by a template editor.
TextReader Represents a reader that can read a sequential series of characters.
TextWriter Represents a writer that can write a sequential series of characters. This class is abstract.
Timer Provides a mechanism for executing a method at specified intervals. This class cannot be inherited.
ToBase64Transform Converts a CryptoStream to base 64.
TraceListener Provides the abstract (MustInherit in Visual Basic) base class for the listeners who monitor trace and debug output.
UdpClient Provides User Datagram Protocol (UDP) network services.
WaitHandle Encapsulates operating system-specific objects that wait for exclusive access to shared resources.
WebResponse Provides a response from a Uniform Resource Identifier (URI). This is an abstract (MustInherit in Visual Basic) class.

Remarks

The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used, however, it is unpredictable when garbage collection will occur. Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, and open files and streams.

Use the Dispose method of this interface to explicitly release unmanaged resources in conjunction with the garbage collector. The consumer of an object can call this method when the object is no longer needed.

It is a version breaking change to add the IDisposable interface to an existing class, as it changes the semantics of the class.

For a detailed discussion about how this interface and the Object.Finalize method are used, see the Programming for Garbage Collection and Implementing a Dispose Method topics.

Example

[Visual Basic] 
Imports System
Imports System.ComponentModel

' The following example demonstrates how to create
' a resource class that implements the IDisposable interface
' and the IDisposable.Dispose method.
Public Class DisposeExample

   ' A class that implements IDisposable.
   ' By implementing IDisposable, you are announcing that 
   ' instances of this type allocate scarce resources.
   Public Class MyResource
      Implements IDisposable
      ' Pointer to an external unmanaged resource.
      Private handle As IntPtr
      ' Other managed resource this class uses.
      Private component As component
      ' Track whether Dispose has been called.
      Private disposed As Boolean = False

      ' The class constructor.
      Public Sub New(ByVal handle As IntPtr)
         Me.handle = handle
      End Sub

      ' Implement IDisposable.
      ' Do not make this method virtual.
      ' A derived class should not be able to override this method.
      Public Overloads Sub Dispose() Implements IDisposable.Dispose
         Dispose(True)
         ' This object will be cleaned up by the Dispose method.
         ' Therefore, you should call GC.SupressFinalize to
         ' take this object off the finalization queue 
         ' and prevent finalization code for this object
         ' from executing a second time.
         GC.SuppressFinalize(Me)
      End Sub

      ' Dispose(bool disposing) executes in two distinct scenarios.
      ' If disposing equals true, the method has been called directly
      ' or indirectly by a user's code. Managed and unmanaged resources
      ' can be disposed.
      ' If disposing equals false, the method has been called by the 
      ' runtime from inside the finalizer and you should not reference 
      ' other objects. Only unmanaged resources can be disposed.
      Private Overloads Sub Dispose(ByVal disposing As Boolean)
         ' Check to see if Dispose has already been called.
         If Not Me.disposed Then
            ' If disposing equals true, dispose all managed 
            ' and unmanaged resources.
            If disposing Then
               ' Dispose managed resources.
               component.Dispose()
            End If

            ' Call the appropriate methods to clean up 
            ' unmanaged resources here.
            ' If disposing is false, 
            ' only the following code is executed.
            CloseHandle(handle)
            handle = IntPtr.Zero
         End If
         disposed = True
      End Sub

      ' Use interop to call the method necessary  
      ' to clean up the unmanaged resource.
      <System.Runtime.InteropServices.DllImport("Kernel32")> _
      Private Shared Function CloseHandle(ByVal handle As IntPtr) As [Boolean]
      End Function

      ' This finalizer will run only if the Dispose method 
      ' does not get called.
      ' It gives your base class the opportunity to finalize.
      ' Do not provide finalize methods in types derived from this class.
      Protected Overrides Sub Finalize()
         ' Do not re-create Dispose clean-up code here.
         ' Calling Dispose(false) is optimal in terms of
         ' readability and maintainability.
         Dispose(False)
         MyBase.Finalize()
      End Sub
   End Class

   Public Shared Sub Main()
      ' Insert code here to create
      ' and use the MyResource object.
   End Sub

End Class

[C#] 
using System;
using System.ComponentModel;

// The following example demonstrates how to create
// a resource class that implements the IDisposable interface
// and the IDisposable.Dispose method.

public class DisposeExample
{
    // A base class that implements IDisposable.
    // By implementing IDisposable, you are announcing that 
    // instances of this type allocate scarce resources.
    public class MyResource: IDisposable
    {
        // Pointer to an external unmanaged resource.
        private IntPtr handle;
        // Other managed resource this class uses.
        private Component component = new Component();
        // Track whether Dispose has been called.
        private bool disposed = false;

        // The class constructor.
        public MyResource(IntPtr handle)
        {
            this.handle = handle;
        }

        // Implement IDisposable.
        // Do not make this method virtual.
        // A derived class should not be able to override this method.
        public void Dispose()
        {
            Dispose(true);
            // This object will be cleaned up by the Dispose method.
            // Therefore, you should call GC.SupressFinalize to
            // take this object off the finalization queue 
            // and prevent finalization code for this object
            // from executing a second time.
            GC.SuppressFinalize(this);
        }

        // Dispose(bool disposing) executes in two distinct scenarios.
        // If disposing equals true, the method has been called directly
        // or indirectly by a user's code. Managed and unmanaged resources
        // can be disposed.
        // If disposing equals false, the method has been called by the 
        // runtime from inside the finalizer and you should not reference 
        // other objects. Only unmanaged resources can be disposed.
        private void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if(!this.disposed)
            {
                // If disposing equals true, dispose all managed 
                // and unmanaged resources.
                if(disposing)
                {
                // Dispose managed resources.
                component.Dispose();
                }
             
                // Call the appropriate methods to clean up 
                // unmanaged resources here.
                // If disposing is false, 
                // only the following code is executed.
                CloseHandle(handle);
                handle = IntPtr.Zero;            
            }
            disposed = true;         
        }

        // Use interop to call the method necessary  
        // to clean up the unmanaged resource.
        [System.Runtime.InteropServices.DllImport("Kernel32")]
        private extern static Boolean CloseHandle(IntPtr handle);

        // Use C# destructor syntax for finalization code.
        // This destructor will run only if the Dispose method 
        // does not get called.
        // It gives your base class the opportunity to finalize.
        // Do not provide destructors in types derived from this class.
        ~MyResource()      
        {
            // Do not re-create Dispose clean-up code here.
            // Calling Dispose(false) is optimal in terms of
            // readability and maintainability.
            Dispose(false);
        }
    }
    public static void Main()
    {
        // Insert code here to create
        // and use the MyResource object.   
    }
}

[C++] 
#using <mscorlib.dll>
#using <System.dll>

using namespace System;
using namespace System::ComponentModel;

// The following example demonstrates how to create
// a resource class that implements the IDisposable interface
// and the IDisposable.Dispose method.

// A base class that implements IDisposable.
// By implementing IDisposable, you are announcing that
// instances of this type allocate scarce resources.
public __gc class MyResource : public IDisposable {
   // Pointer to an external unmanaged resource.
   IntPtr  handle;
   // Other managed resource this class uses.
   Component*  component;
   // Track whether Dispose has been called.
   bool disposed;
public:
   // The class constructor.
   MyResource(IntPtr handle) {
      this->handle = handle;
      disposed = false;
   }

   // Implement IDisposable*
   // Do not make this method virtual.
   // A derived class should not be able to  this method.
   void Dispose() {
      Dispose(true);
      // This object will be cleaned up by the Dispose method.
      // Therefore, you should call GC::SupressFinalize to
      // take this object off the finalization queue
      // and prevent finalization code for this object
      // from executing a second time.
      GC::SuppressFinalize(this);
   }

private:
   // Dispose(bool disposing) executes in two distinct scenarios.
   // If disposing equals true, the method has been called directly
   // or indirectly by a user's code. Managed and unmanaged resources
   // can be disposed.
   // If disposing equals false, the method has been called by the
   // runtime from inside the finalizer and you should not reference
   // other objects. Only unmanaged resources can be disposed.
   void Dispose(bool disposing) {
      // Check to see if Dispose has already been called.
      if (!this->disposed) {
         // If disposing equals true, dispose all managed
         // and unmanaged resources.
         if (disposing) {
            // Dispose managed resources.
            component->Dispose();
         }

         // Call the appropriate methods to clean up
         // unmanaged resources here.
         // If disposing is false,
         // only the following code is executed.
         CloseHandle(handle);
         handle = IntPtr::Zero;
      }
      disposed = true;
   }

   // Use interop to call the method necessary
   // to clean up the unmanaged resource.
   [System::Runtime::InteropServices::DllImport(S"Kernel32")]
   static Boolean CloseHandle(IntPtr handle);

   // Use C# destructor syntax for finalization code.
   // This destructor will run only if the Dispose method
   // does not get called.
   // It gives your base class the opportunity to finalize.
   // Do not provide destructors in types derived from this class.
   ~MyResource() {
      // Do not re-create Dispose clean-up code here.
      // Calling Dispose(false) is optimal in terms of
      // readability and maintainability.
      Dispose(false);
   }
};

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Namespace: System

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework

Assembly: Mscorlib (in Mscorlib.dll)

See Also

IDisposable Members | System Namespace

Show:
© 2014 Microsoft