Section 8.8. Destroying Objects

   

8.8 Destroying Objects

Unlike many other programming languages (C, C++, Pascal, etc.), VB.NET provides garbage collection. Your objects are automatically destroyed when you are done with them. You do not need to worry about cleaning up after your objects unless you use unmanaged resources. An unmanaged resource is an operating system feature outside of the .NET Framework, such as a file handle or a database connection. If you do control an unmanaged resource, you will need to explicitly free that resource when you are done with it. Implicit control over this resource is provided with a Finalize( ) method, which will be called by the garbage collector when your object is destroyed :

 Protected Overrides Sub Finalize( )     ' release non-managed resources     MyBase.Finalize( )   End Sub 

The Protected keyword is described in Section 8.1.5 earlier in this chapter. For a discussion of the Overrides keyword, see Chapter 13.

It is not legal to call Finalize( ) explicitly. Finalize( ) will be called by the garbage collector. If you do handle precious unmanaged resources (such as file handles) that you want to close and dispose of as quickly as possible, you ought to implement the IDisposable interface. (You will learn more about interfaces in Chapter 13.) The IDisposable interface requires that you create a method named Dispose( ) that will be called by your clients .

If you provide a Dispose( ) method, you should stop the garbage collector from calling your object's destructor. To stop the garbage collector, you call the shared method GC.SuppressFinalize( ), passing in the Me reference for your object. Your Finalize( ) method can then call your Dispose( ) method. Thus, you might write:

 Public Class Testing    Implements IDisposable    Dim is_disposed As Boolean = False        Protected Sub Dispose(ByVal disposing As Boolean)       If Not is_disposed Then          If disposing Then             Console.WriteLine("Not in destructor, OK to reference other objects")          End If          ' perform cleanup for this object          Console.WriteLine("Disposing...")       End If       Me.is_disposed = True    End Sub        Public Sub Dispose( ) Implements IDisposable.Dispose       Dispose(True)       'tell the GC not to finalize       GC.SuppressFinalize(Me)    End Sub        Protected Overrides Sub Finalize( )       Dispose(False)       Console.WriteLine("In destructor.")    End Sub End Class 
   


Learning Visual Basic. NET
Learning Visual Basic .Net
ISBN: 0596003862
EAN: 2147483647
Year: 2002
Pages: 153
Authors: Jesse Liberty

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net