Under the Hood of .NET Memory Management - Simple Talk
Under the Hood of .NET Memory Management - Simple Talk
Under the Hood of .NET Memory Management - Simple Talk
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Chapter 2: The <strong>Simple</strong> Heap Model<br />
Periodically, <strong>the</strong> finalization thread will run, and it will iterate through all objects pointed<br />
to by references in <strong>the</strong> fReachable queue, calling <strong>the</strong> Finalize method or destructor<br />
on each one and removing its reference from fReachable. Only <strong>the</strong>n will <strong>the</strong> finalizable<br />
object be rootless and available for collection.<br />
In <strong>the</strong> earlier example, Object Z made it to Gen 2, where it could potentially have<br />
remained for a while. What we don't know is whe<strong>the</strong>r Object Z was actually needed for all<br />
that time, or whe<strong>the</strong>r its finalization was just poorly implemented.<br />
This doesn't mean that finalizers are bad; in fact, <strong>the</strong>y are absolutely essential. But you<br />
do need to write your finalization mechanism in <strong>the</strong> right way, which is what comes next.<br />
Improving finalization efficiency<br />
A simple pattern you can follow to avoid <strong>the</strong> finalization problem, is by implementing <strong>the</strong><br />
IDisposable interface on your class and applying <strong>the</strong> following Dispose pattern:<br />
public void Dispose()<br />
{<br />
Cleanup(true);<br />
GC.SuppressFinalize(this);<br />
}<br />
private void Cleanup(bool disposing)<br />
{<br />
if (!disposing)<br />
{<br />
// Thread-specific code goes here<br />
}<br />
// Resource Cleanup goes here<br />
}<br />
public void Finalize()<br />
{<br />
Cleanup(false);<br />
Listing 2.4: Improving finalization efficiency using Dispose.<br />
53