30.06.2013 Views

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

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 6: A Few More Advanced Topics<br />

}<br />

if (stringPointer != IntPtr.Zero )<br />

Marshal.FreeHGlobal(stringPointer );<br />

Listing 6.9: Explicitly free unmanaged memory that has been allocated.<br />

In this example, you would effectively leak 32 bytes <strong>of</strong> data every time this method is<br />

called, in addition to however many bytes were needed to hold <strong>the</strong> stringValue. This<br />

could easily become a memory flood instead <strong>of</strong> just a leak.<br />

As a rule, I'd recommend that you isolate code that allocates or uses marshaled memory<br />

to a central location. This type <strong>of</strong> logic should not be spread throughout your code<br />

base, but ra<strong>the</strong>r isolated to proxy classes providing access to <strong>the</strong> desired unmanaged<br />

functionality. Additionally, this code should be routinely monitored to ensure that all best<br />

practices are consistently followed, because <strong>the</strong>se code constructs are easily abused.<br />

Conclusion<br />

The world <strong>of</strong> s<strong>of</strong>tware advances at an amazing pace. Fortunately for us, <strong>the</strong> .<strong>NET</strong><br />

framework advances at an equally amazing pace. As hardware advancements have made<br />

64-bit architectures more prevalent, <strong>the</strong> framework kept pace, to provide excellent<br />

support for 64-bit programs. Future versions will assuredly continue to keep pace,<br />

providing ever-improving support for parallel and asynchronous programming to take<br />

advantage <strong>of</strong> similar hardware advances in multicore technology.<br />

The GC is a pillar <strong>of</strong> <strong>the</strong> .<strong>NET</strong> framework, separating it from all o<strong>the</strong>r development<br />

platforms; indeed <strong>the</strong> success <strong>of</strong> <strong>the</strong> framework is directly tied to how effective <strong>the</strong><br />

GC is. The GC's effectiveness is at least partly a function <strong>of</strong> how well it stays out <strong>of</strong> <strong>the</strong><br />

way <strong>of</strong> developers, and avoids being overtly noticed by <strong>the</strong> user. Each new version <strong>of</strong><br />

.<strong>NET</strong> has set out to make <strong>the</strong> GC less and less intrusive, yet more effective at managing<br />

memory – a powerful combination.<br />

195

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!