Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))

Problem

You've created an object that allocates its own resources, and you're ready to get rid of it. What's the correct method?

Solution

Visual Basic provides three primary methods for getting rid of objects that implement the IDisposable interface:

  • Call the object's Dispose() method, exposed by the IDisposable interface and implemented by the object's type. This is the most direct method of freeing resources. The object should not be used once Dispose() has been called.

  • Use Visual Basic's Using statement. This block statement automatically calls the object's Dispose() method on your behalf when the block ends, or execution jumps out of the block for any reason.

    Many of the GDI+ drawing objects implement IDisposable and should be disposed of properly when no longer in use. The Pen object is one such class. The following code uses the Using statement to declare and properly dispose of a Pen object:

    Using workPen As New Pen(Color.Red) ' ----- Add drawing code here using that red pen. End Using ' ----- workPen has been released and is unavailable.

  • Let the object go out of scope, or set it to Nothing. This practice is usually undesirable because the garbage-collection process, and not you, will control when the additional resources get released.

Discussion

The constructor for a class may allocate shared resources that need to be properly released as quickly as possible when no longer needed. Some classes implement their own custom method for doing this, such as including a "release all resources" method. You must examine and follow the documented standards for such objects.

Fortunately, most objects that hold such external or shared resources implement the System.IDisposable interface. This interface exposes a standard Dispose() method that your code or other standardized generic components can call to free important resources. You can add IDisposable to your own classes, as follows:

Class SomeClass Implements IDisposable Protected Overridable Sub Dispose( ) _ Implements IDisposable.Dispose ' ----- Add cleanup code here. End Sub End Class

For classes that do not allocate shared or external resources, or where holding on to such resources for a long time will not degrade application or system performance, the standard Finalize() deconstructor may be used to free held resources. For such classes, no special processing is needed to destroy the object. Simply wait for the object to be released on its own, or set it to Nothing.

If you implement IDisposable on a custom class, you should also override the Finalize() method to ensure that resources are freed even if the user of the class forgets to call Dispose():

Protected Overrides Sub Finalize( ) ' ----- Add cleanup guarantee here. End Sub

Категории