Garbage Collection and Destructors
Every object you create uses various system resources, such as memory. In many programming languages, these system resources are reserved for the object's use until they are explicitly released. If all the references to the object that manages the resource are lost before the resource is explicitly released, the application can no longer access the resource to release it. This is known as a resource leak.
We need a disciplined way to give resources back to the system when they are no longer needed, thus avoiding resource leaks. The Common Language Runtime (CLR) performs automatic memory management by using a garbage collector to reclaim the memory occupied by objects that are no longer in use, so the memory can be used for other objects. When there are no more references to an object, the object becomes eligible for destruction. Every object has a special member, called a destructor, that is invoked by the garbage collector to perform termination housekeeping on an object just before the garbage collector reclaims the object's memory. A destructor is declared like a parameterless constructor, except that its name is the class name, preceded by a tilde (~), and it has no access modifier in its header. After the garbage collector calls the object's destructor, the object becomes eligible for garbage collection. The memory for such an object can be reclaimed by the garbage collector. Memory leaks, which are common in other languages like C and C++ (because memory is not automatically reclaimed in those languages), are less likely in C# (but some can still happen in subtle ways). Other types of resource leaks can occur. For example, an application could open a file on disk to modify the file's contents. If the application does not close the file, no other application can modify (or possibly even use) the file until the application that opened the file completes.
A problem with the garbage collector is that it is not guaranteed to perform its tasks at a specified time. Therefore, the garbage collector may call the destructor any time after the object becomes eligible for destruction, and may reclaim the memory any time after the destructor executes. In fact, neither may happen before an application terminates. Thus, it is unclear if, or when, the destructor will be called. For this reason, most programmers should avoid using destructors. In Section 9.10, we demonstrate a situation in which we use a destructor. We will also demonstrate some of the static methods of class GC (in namespace System), which allow us to exert some control over the garbage collector and when destructors are called.
static Class Members
|