Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
You need to create an object that frees unmanaged resources deterministically.
Implement the IDisposable pattern. Clients will call the Dispose method to release the object’s resources.
The IDisposable interface defines a single method, called Dispose. In this method, the class will release all its unmanaged resources. For best performance, when implementing IDisposable you should follow these best practices:
Suppress garbage collector finalization for the object, provided it has no managed resources to release.
Implement a finalizer that calls your Dispose method when the object is garbage collected. That way, if your object is released without Dispose being called (a common error), the resources will still be freed eventually.
Call Dispose on any contained objects, provided the Dispose method is triggered directly and not called by the garbage collector (in which case a contained object could still be in use).
Be aware that it’s of no use to implement Dispose with managed resources, because even if you set the variables to Nothing, the garbage collector still needs to run to reclaim the memory.
Here’s how you would apply the disposable pattern in a custom class:
Public Class MyDisposableClass
Implements IDisposable
' Implement IDisposable.
' This is the method the client calls to dispose the object.
Public Overloads Sub Dispose() Implements System.IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
' This method is only called if the object is garbage
' collected without being properly disposed.
Protected Overrides Sub Finalize()
Dispose(False)
End Sub
' The custom code for releasing resources goes here.
Protected Overridable Overloads Sub Dispose(ByVal disposing As Boolean)
If disposing Then
' Disposal was triggered manually by the client.
' Call Dispose() on any contained classes.
End If
' Release unmanaged resources.
' Set large member variables to Nothing (null).
End Sub
End Class
Notice that there’s no way to force a client to call Dispose. Using a finalizer instead of a Dispose method won’t help because the unmanaged resources won’t be released until the garbage collector is activated or the application ends. On a system where memory is plentiful, this can take a long time!
You can also implement IDisposable indirectly by implementing System.ComponentModel.IComponent, which extends IDisposable, or inheriting from System.ComponentModel.Component, as described in recipe 4.6.
Note
To see a disposable object in action, run the sample code for this recipe. It uses a disposable object that displays Console messages to indicate its state. You’ll be able to contrast a properly disposed object (which releases its resources immediately) with one that is just abandoned by setting the object reference to Nothing (which typically won’t release its resources until the application ends).