Defines a method to release allocated resources.
Assembly: mscorlib (in mscorlib.dll)
<ComVisibleAttribute(True)> _ Public Interface IDisposable
[ComVisibleAttribute(true)] public interface IDisposable
[ComVisibleAttribute(true)] public interface class IDisposable
[<ComVisibleAttribute(true)>] type IDisposable = interface end
The IDisposable type exposes the following members.
| Name | Description | |
|---|---|---|
|
Dispose | Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. |
The primary use of this interface is to release unmanaged resources. The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it is not possible to predict when garbage collection will occur. Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or 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, because it changes the semantics of the class.
Important
|
|---|
|
C++ programmers should read Destructors and Finalizers in Visual C++. In the .NET Framework version, the C++ compiler provides support for implementing deterministic disposal of resources and does not allow direct implementation of the Dispose method. |
For a detailed discussion about how this interface and the Object.Finalize method are used, see the Garbage Collection and Implementing a Dispose Method topics.
Calling the IDisposable Interface
When calling a class that implements the IDisposable interface, use the try/finally pattern to make sure that unmanaged resources are disposed of even if an exception interrupts your application.
For more information about the try/finally pattern, see Try...Catch...Finally Statement (Visual Basic), try-finally (C# Reference), or try-finally Statement (C).
Note that you can use the using statement (Using in Visual Basic) instead of the try/finally pattern. For more information, see the Using Statement (Visual Basic) documentation or the using Statement (C# Reference) documentation.
The following example demonstrates how to create a resource class that implements the IDisposable interface.
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. Protected Overridable 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 ' Note disposing has been done. disposed = True End If 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
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. protected virtual 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; // Note disposing has been done. 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. } }
#using <System.dll> #using <System.Windows.Forms.dll> using namespace System; using namespace System::ComponentModel; using namespace System::Windows::Forms; // The following example demonstrates how to create a class that // implements the IDisposable interface and the IDisposable.Dispose // method with finalization to clean up unmanaged resources. // public ref class MyResource: public IDisposable { private: // Pointer to an external unmanaged resource. IntPtr handle; // A managed resource this class uses. Component^ component; // Track whether Dispose has been called. bool disposed; public: // The class constructor. MyResource( IntPtr handle, Component^ component ) { this->handle = handle; this->component = component; disposed = false; } // This method is called if the user explicitly disposes of the // object (by calling the Dispose method in other managed languages, // or the destructor in C++). The compiler emits as a call to // GC::SuppressFinalize( this ) for you, so there is no need to // call it here. ~MyResource() { // Dispose of managed resources. component->~Component(); // Call C++ finalizer to clean up unmanaged resources. this->!MyResource(); // Mark the class as disposed. This flag allows you to throw an // exception if a disposed object is accessed. disposed = true; } // Use interop to call the method necessary to clean up the // unmanaged resource. // [System::Runtime::InteropServices::DllImport("Kernel32")] static Boolean CloseHandle( IntPtr handle ); // The C++ finalizer destructor ensures that unmanaged resources get // released if the user releases the object without explicitly // disposing of it. // !MyResource() { // Call the appropriate methods to clean up unmanaged // resources here. If disposing is false when Dispose(bool, // disposing) is called, only the following code is executed. CloseHandle( handle ); handle = IntPtr::Zero; } }; void main() { // Insert code here to create and use the MyResource object. MyResource^ mr = gcnew MyResource((IntPtr) 42, (Component^) gcnew Button()); mr->~MyResource(); }
.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0.NET Framework Client Profile
Supported in: 4, 3.5 SP1Portable Class Library
Supported in: Portable Class LibraryWindows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Reference
namespace ????
{
public class MyResource : IDisposable
{
private bool _disposed = false;
~MyResource()
{
Dispose(false);
}
#region IDisposable
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
// TODO: dispose managed resources
}
// TODO: Call the appropriate methods to clean up unmanaged resources here
// we're done
_disposed = true;
}
}
}-- Luke Puplett - Nice one! I made it Dispose protected virtual, Tip: drag and drop this snippet into your Toolbox (easier than creating actual snippets)
Here's my lock-free (thread safe) abstract implementation of IDisposable as suggested in the article. It lets you inherit from it to make your own IDisposable classes by simply filling in two cleanup methods: DisposeManagedResources and DisposeUnmanagedResources.
I use it instead of IDisposable since the pattern is very easy to get wrong.
gods-love-is here.in crist name amen
using System; using System.Threading;
namespace ??????
{
/// <summary>Provides a thread-safe, abstract implementation of IDisposable.</summary>
public abstract class Disposable : IDisposable
{
/// <summary>Integer flag for whether Dispose has been called or not. 0 = false, 1 = true.</summary>
protected volatile int _disposed;
/// <summary>Disposes of the managed and unmanaged resources held by this Disposable.</summary>
public void Dispose()
{
if (Interlocked.CompareExchange(ref _disposed, 1, 0) == 0)
{
GC.SuppressFinalize(this);
DisposeUnmanagedResources();
DisposeManagedResources();
}
}
/// <summary>
/// Disposes the managed resources held by this object. You may clean up managed resources in this method,
/// such as instances of IDisposable. This should never be called by your class except to call the base
/// (non-abstract) version of this method within the derived version. This method will only ever be called once.
/// </summary>
protected abstract void DisposeManagedResources();
/// <summary>
/// Disposes the unmanaged resources held by this object. Do not clean up anything with a finalizer in
/// this method. This should never be called by your class except to call the base (non-abstract) version
/// of this method within the derived version. This method will only ever be called once.
/// </summary>
protected abstract void DisposeUnmanagedResources();
/// <summary>Calls DisposeUnmanagedResources. Managed resources cannot be cleaned up in finalizers.</summary>
~Disposable() { DisposeUnmanagedResources(); }
}
}
Remember to make it available to code in derived types so you can call base.Dispose(disposing) :
protected virtual void Dispose(...
--True! I'll get that changed. (djangow, MSDG)
CA1805: Do not initialize unnecessarily: http://msdn.microsoft.com/library/ms182274(VS.90).aspx
You can find more about this and about the simplified pattern (when you don't have the unmanaged resources in your class) in my blog post: http://dixond.blogspot.com/2010/08/everything-what-you-might-want-to-know.html
Important