Resource Management

All objects consume system resources such as memory, file handles, and database connections. The Common Language Runtime (CLR) manages resources automatically, and usually you do not need to worry about releasing unneeded objects. However, understanding how resource management works can help you design your applications to be more efficient.

Garbage Collection

The CLR uses a system called garbage collection to manage allocated resources. The system garbage collector releases an object's resources when that object can no longer be reached by any running code in your application. The garbage collection algorithm is nondeterministic, so you cannot determine when the CLR will release an object's resources. The following sections describe some of the changes to the way resources are managed in Visual Basic.

Assigning Objects to Nothing

Nothing is a keyword used by Visual Basic to indicate that an object variable does not contain a reference to an object. Previous versions of Visual Basic encouraged you to assign unused objects to Nothing to disassociate the object variable from the object and release resources. You can still assign unused objects to Nothing, but because of the way Visual Basic manages resources, this process does not guarantee that objects will be released immediately. Generally speaking, you should only assign long-lived objects—such as shared members or global variables—to Nothing.

Dispose

Some objects support a method named Dispose; its purpose is to release system resources more expeditiously. Classes that support the Dispose method must implement the IDisposable interface. The Dispose method needs to be explicitly called when you want to release object resources. For example:

ThisObject.Dispose()

Finalize

Another method supported by some classes, Finalize, runs automatically when an object is released and can be used to perform other cleanup tasks. The Finalize method is similar to the Class_Terminate() method used in previous versions of Visual Basic. After an object becomes inaccessible, the CLR will eventually call the object's Finalize method. Because the garbage collection algorithm is nondeterministic, the Finalize method might be called immediately, or it might be called several hours later.

See Also

Concepts

Object Lifetime: How Objects Are Created and Destroyed

Initialization and Termination of Components

Reference

Nothing (Visual Basic)

Dispose

IDisposable