Chapter 5. Garbage Collection Gotchas


Garbage collection, in general, is the process of cleaning up the memory and resources used by an object when it is no longer needed. For instance, in C++, you write a destructor to take care of this. There are two tasks that the destructor typically performs:

  • deletes other objects to which the object holds pointers

  • closes handles to resources

.NET, on the contrary, provides automatic garbage collection. It largely removes the burden of memory management from the programmer. But what does automatic garbage collection really do? It just reclaims the memory used by objects. What about the cleanup of resources?

When I say resources here, I mean unmanaged resources: those that .NET will not be able to release automatically. For example, resources created while interacting with a COM component or while using PInvoke to access some Win32 API. You, the programmer, have to write code to properly dispose of these resources.

The Finalize() method is provided for this purpose. When an object is garbage-collected, the CLR takes care of memory-related cleanup and calls the object's Finalize() method, giving it an opportunity to release any unmanaged resources.

In VB.NET, you have to actually write the Finalize() method. In C#, you don't. Instead, you write a specialized pseudo-destructor with the ~NameOfYourClass() syntax, as in C++. But don't confuse the C# pseudo-destructor with the C++ destructor. The generated MSIL does not contain any destructor. The C# compiler creates the Finalize() method using the code you write in the specialized pseudo-destructor.

Throughout the rest of this chapter, whenever I refer to the "Finalize() method," I am referring to the Finalize() method in VB.NET and the pseudo-destructor in C#.


The CLR is responsible for reclaiming memory; your object's Finalize() method releases unmanaged resources. This appears reasonable and straightforward, but a number of practical issues surface during development. This chapter focuses on concerns related to garbage collection, and how to write code that handles it effectively.



    .NET Gotachas
    .NET Gotachas
    ISBN: N/A
    EAN: N/A
    Year: 2005
    Pages: 126

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net