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# ...
Get .NET Gotchas 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.