Memory Management

This section looks at one of the larger underlying elements of managed code. One of the reasons why .NET applications are referred to as “managed” is that memory deallocation is handled automatically by the system. Developers are accustomed to worrying about memory management only in an abstract sense. The basic rule has been that every object created and every section of memory allocated needs to be released (destroyed). The CLR introduces a garbage collector (GC), which simplifies this paradigm. Gone are the days when a misbehaving component—for example, one that fails to properly dispose of its object references or allocates and never releases memory—could crash a machine.

However, the use of a GC introduces new questions about when and if objects need to be explicitly cleaned up. There are two elements in manually writing code to allocate and deallocate memory and system resources. The first is the release of any shared resources, such as file handles and database connections. This type of activity needs to be managed explicitly and is discussed shortly. The second element of manual memory management involves letting the system know when memory is no longer in use by your application. Developers in unmanaged languages like C are accustomed to explicitly disposing of memory references. While you can explicitly show your intent to destroy the object by setting it to Nothing manually, this is not good practice.

The .NET GC automatically manages the cleanup of ...

Get Professional Visual Basic 2012 and .NET 4.5 Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.