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 6: A Few More Advanced Topics<br />
public void Parse ()<br />
{<br />
XmlDocument document = null;<br />
if (_weak.IsAlive )<br />
document = _weak.Target as XmlDocument;<br />
if (document == null)<br />
{<br />
// log that weak reference was lost<br />
// recreate <strong>the</strong> document<br />
}<br />
// handle <strong>the</strong> parsing<br />
}<br />
Listing 6.6: Testing to see if <strong>the</strong> weak reference is still valid.<br />
If you find that you have to recreate <strong>the</strong> object frequently, or if your original estimate for<br />
how much time it takes to recreate <strong>the</strong> data is inaccurate, you may want to revisit <strong>the</strong><br />
choice to use weak references. In almost all cases, you will be better served with reviewing<br />
your instrumentation data periodically to ensure that you are still getting <strong>the</strong> results that<br />
you expect. If you don't get <strong>the</strong> results you expect, you will almost certainly simplify your<br />
application logic by removing <strong>the</strong> weak reference logic.<br />
Marshaling<br />
Occasionally you may need to access functionality that is exposed in a native DLL. This is<br />
not common, because <strong>the</strong> CLR is quite extensive, but it is a good idea to understand what<br />
happens behind <strong>the</strong> scenes. Also if you use .<strong>NET</strong> Reflector to browse <strong>the</strong> source code for<br />
<strong>the</strong> framework, you will find this crop up from time to time, and you need to know what<br />
is going on.<br />
Marshaling can definitely have a memory impact. The MSDN documentation<br />
makes it clear when it states that <strong>the</strong> Marshal class "provides a collection <strong>of</strong> methods<br />
for allocating unmanaged memory, copying unmanaged memory blocks, and converting<br />
192