10.8 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’re explicitly released by the programmer. If all the references to the object that manages a resource are lost before the resource is explicitly released, the app can no longer access the resource to release it. This is known as a resource leak.

To avoid resource leaks, we need a disciplined way to give resources back to the system when they’re no longer needed. The Common Language Runtime (CLR) performs automatic memory management by using a garbage collector that reclaims the memory occupied by objects 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’s invoked by the garbage collector to perform termination housekeeping on an object 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 such as 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 app could open a file on disk to modify its contents. If the app does not close the file, no other app can modify (or possibly even use) the file until the app that opened it terminates.

A problem with the garbage collector is it doesn’t guarantee that it will 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, it’s possible that neither will happen before the app terminates. Thus, it’s unclear whether, or when, the destructor will be called. For this reason, destructors are rarely used.

Software Engineering Observation 10.9

A class that uses resources, such as files on disk, should provide a method to eventually release the resources. Many Framework Class Library classes provide Close or Dispose methods for this purpose. Section 13.6 introduces the Dispose method, which is then used in many later examples. Close methods are typically used with objects that are associated with files (Chapter 17) and other types of so-called streams of data.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset