Resource Management and IDisposable

I l @ ve RuBoard

Resource Management and IDisposable

Visual Basic .NET has a new twist on resource management. The CLR provides a resource management mechanism known as garbage collection to free the developer from most memory management tasks . But it does not come without a price, nor does it completely free you from dealing with memory management issues. In some ways, garbage collection forces you to be more aware of which objects require manual intervention to ensure that resources are released in an appropriate manner. For the most part, you do not need to worry about when objects are destroyed .

In Visual Basic 6.0, when all object variables that refer to an object are assigned to Nothing , the memory and system resources associated with the object are freed immediately. You know exactly when the object was freed (deterministic finalization ). The CLR now takes on the responsibility of resource management. This allows developers to concentrate on improving their applications instead of writing lots of resource management and cleanup code.

This requires a change in coding practices. For example, when you set a variable to Nothing , the object is not destroyed immediately. It will be destroyed at some later time (to be determined by the garbage collector). For the most part, this shouldn't affect your application. However, in some scenarios (such as when an application is under stress due to low system resources), it can be a real problem that affects both performance and scalability. In a situation in which performance is critical, it is in your best interests to free resources as soon as you're done with them.

Note

Keep in mind that garbage collector collection cycles are expensive. The idea is to prevent the garbage collector from running too frequently. The more you clean up after yourself, the less work it will have to do and the better your application will perform.


The Garbage Collector

If an application uses unmanaged resources (for example, if it explicitly allocates memory, file handles, or other system resources), the CLR garbage collector will usually have no idea how to free them up. Even when the garbage collector can handle some of these resources, it might not necessarily free them in a timely fashion. It is important to do some manual cleanup, especially if what you're working with represents some physical resource on the machine. Override the Object.Finalize method and free the resources there. (By default, this method does nothing.) However, be aware that because of way the garbage collector works, using the Finalize method affects performance ”so don't use it unless you need to. For more information on this, check out MSDN.

Even if Finalize is overridden and the resources are freed, you have no control over when the garbage collector will start collecting. You call always call System.GC.Collect , but you should never do that in a production environment. CLR resource management is quite complex and the collector knows when to best to run a collection cycle. Your application's performance can be badly hurt if you start calling System.GC.Collect . Be aware that the garbage collector starts when there is a need for managed memory. It has no real control over unmanaged resources. The .NET Framework provides a solution to this problem: the IDisposable interface (discussed next ).

The IDisposable Interface

So how can you tell if an object needs additional cleanup on your part? It's actually pretty simple. All classes in the .NET Framework that allocate resources that should be freed immediately should implement the IDisposable interface. This interface contains only a single method:

 PublicInterfaceIDisposable SubDispose() EndInterface 

If a class you've instantiated implements this interface, you should call Dispose when you're done with it. Pretty simple, right? But what are the advantages of IDisposable ? IDisposable makes it possible to identify all classes that allocate expensive resources, and it provides a simplified, reliable mechanism for freeing all of those resources.

As we already mentioned, many classes in the .NET Framework implement IDisposable . Here's an example that uses the SqlConnection class:

 DimconnAsNewSqlConnection() 'DoStuff conn.Dispose() 

But this is not necessarily reliable. Errors and exceptions are always possibilities, so putting the Dispose call in a Finally block of a Try Catch Finally statement guarantees that your code will always clean up. Our code should look more like this:

 DimconnAsSqlConnection Try conn=NewSqlConnection() 'DoStuff Finally'Weskipthecatchclausebecausewedon'tneedithere. conn.Dispose() EndTry 

This makes sense, but what if you need to implement IDisposable ?

Implementing IDisposable

It's an interesting question: when should a class that you create implement IDisposable ? Here are three common situations in which you should definitely implement the IDisposable interface on a class:

  • When your class contains other classes that implement IDisposable

  • When your class contains instances of COM objects

  • When your class has a reference to an active Win32 resource handle

The simplest implementation of IDisposable would look like the following:

 PublicClassMyDisposableClass ImplementsIDisposable 'Othermembers PublicOverloadsSubDispose()ImplementsIDisposable.Dispose 'ReleaseYourResourcesHere EndSub EndClass 

However, the simplest implementation is not always the most reliable. A more complete implementation would look like the following:

 PublicClassMyDisposableClass ImplementsIDisposable PublicOverloadsSubDispose()ImplementsIDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me)'Noneedcallfinalizer EndSub ProtectedOverridableOverloadsSubDispose(ByValdisposingAsBoolean) IfdisposingThen 'Freemanagedresources EndIf 'Freeunmanagedresources EndSub ProtectedOverridesSubFinalize() Dispose(False) EndSub EndClass 
I l @ ve RuBoard


Designing Enterprise Applications with Microsoft Visual Basic .NET
Designing Enterprise Applications with Microsoft Visual Basic .NET (Pro-Developer)
ISBN: 073561721X
EAN: 2147483647
Year: 2002
Pages: 103

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