C Sharp

Object Cleanup and Resource Management

One of the most important features of a component-based system is its ability to provide for cleanup and release of resources upon termination of components. By "cleanup and release of resources," I mean the timely release of references to other components as well as the release of scarce resources or limited resources over which there might be contention, such as database connections, file handles, and communication ports. By "termination," I mean that point at which the object is no longer in use.

In C++, cleanup is straightforward because it's done in the object's destructor, a function defined for every C++ object that automatically executes when the object goes out of scope. In the Microsoft .NET world, object cleanup is handled automatically by the .NET Garbage Collector (GC). This strategy is somewhat controversial because, in contrast to the predictability in C++ of when an object's termination code is executed, the .NET solution is a based on a "lazy" model.

The GC uses threads running in the background that determine when an object is no longer being referenced. Other GC threads are then responsible for running that object's termination code. This is fine in most situations, but it's a less-than-optimal solution when dealing with resources that need to be released in a timely manner and in a predictable order. As you might be aware, this is not an easy problem to solve. In this section, I'll address the problems of object termination and resource management and your role in creating objects withpredictable lifetimes.

(Note that this section is heavily based on an excellent explanation of C# resource management made in an online public forum by Brian Harry, a member of Microsoft's .NET team. Thanks to Brian for allowing my use of his explanation.)

by BrainBellupdated
Advertisement: