<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Talking About Code &#187; Uncategorized</title>
	<atom:link href="http://www.ambersolutions.com.au/dburstin/index.php/category/uncategorized/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.ambersolutions.com.au/dburstin</link>
	<description>A journey of learning, trying and learning some more</description>
	<lastBuildDate>Wed, 05 Feb 2014 05:25:12 +0000</lastBuildDate>
	<language>en-US</language>
		<sy:updatePeriod>hourly</sy:updatePeriod>
		<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.0.38</generator>
	<item>
		<title>Growing IDisposable Guided By Tests</title>
		<link>http://www.ambersolutions.com.au/dburstin/index.php/2014/02/03/growing-idisposable-guided-by-tests/</link>
		<comments>http://www.ambersolutions.com.au/dburstin/index.php/2014/02/03/growing-idisposable-guided-by-tests/#comments</comments>
		<pubDate>Mon, 03 Feb 2014 02:39:54 +0000</pubDate>
		<dc:creator><![CDATA[admin]]></dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.ambersolutions.com.au/dburstin/?p=74</guid>
		<description><![CDATA[My previous post looked at the limitations of the .NET Garbage Collection process. The right way to mitigate these limitations is by allowing an objects owner to call Dispose() to release resources on demand rather than having to wait for the Finalization Queue to run. In this post I will grow a worked example that [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>My <a title=".NET Garbage Collection Primer" href="http://www.ambersolutions.com.au/dburstin/index.php/2014/01/27/net-garbage-collection-primer/">previous post</a> looked at the limitations of the .NET Garbage Collection process. The right way to mitigate these limitations is by allowing an objects owner to call <code>Dispose()</code> to release resources on demand rather than having to wait for the Finalization Queue to run. In this post I will grow a worked example that conforms to the basic design pattern for implementing Dispose. Tests will drive the design of the sample class to ensure that:</p>
<ul>
<li>when the Finalizer is called it releases all unmanaged resources</li>
<li>when the Finalizer is called it does NOT Dispose its managed resources (remember that the order of finalization is not guaranteed, so the managed resource may already have been finalized)</li>
<li>when <code>Dispose()</code> is called all unmanaged resources are released</li>
<li>when <code>Dispose()</code> is called all managed Disposable objects are Disposed</li>
</ul>
<p>To conform to the<a href="http://msdn.microsoft.com/en-us/library/system.idisposable(v=vs.110).aspx" target="_blank"> IDisposable design pattern</a>, the sample class must also:</p>
<ul>
<li>implement IDisposable</li>
<li>provide a <code>protected virtual Dispose(bool disposing)</code> method</li>
<li>the <code>Dispose()</code> method must call <code>Dispose(true)</code></li>
<li>the <code>Dispose()</code> method must suppress finalization</li>
<li>if a finalizer is needed, it must call <code>Dispose(false)</code></li>
<li>handle <code>Dispose()</code> being called multiple times</li>
<li>throw an ObjectDisposedException in any other public method tries to access disposed objects</li>
</ul>
<p>For these tests I will use <a href="http://xunit.codeplex.com/" target="_blank">xUnit </a>and <a href="http://fluentassertions.codeplex.com/" target="_blank">FluentAssertions</a>.</p>
<h5>Sample class</h5>
<p>We begin with a sample class that owns an unmanaged resource (in this case a block of memory allocated from the unmanaged COM task allocator) as well as a disposable managed resource (in this case a MemoryStream).</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> ResourceOwner
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">protected</span> IntPtr AnUnmanagedResource <span style="color: #008000;">=</span> Marshal<span style="color: #008000;">.</span><span style="color: #0000FF;">StringToCoTaskMemAuto</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Foo&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF; font-weight: bold;">protected</span> MemoryStream ADisposableResource <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> MemoryStream<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<h5>Test 1: When the Finalizer is called it releases all unmanaged resources</h5>
<p>Ideally the test would simply call the Finalizer and then check that the unmanaged resource has been released. Unfortunately there is no way to call the Finalizer. The best we can do is use a testing strategy called &#8220;<a title="It's actually an anti-pattern. Read why here." href="http://c2.com/cgi/wiki?SubclassToTestAntiPattern" target="_blank">subclass to test</a>&#8220;, create a method to mimic the Finalizer and visually ensure that it and the Finalizer are always in sync. Terrible, I know, but I can&#8217;t think of any other way. <a title="Dependency Injection" href="http://en.wikipedia.org/wiki/Dependency_injection" target="_blank">DI</a> won&#8217;t work because if we inject the finalizable resources then the ResourceOwner won&#8217;t own them so shouldn&#8217;t dispose of them.  Subclassing also allows us to spy on the non-public resources owned by the base class. It is important to remember that the subclass is part of the test suite, not the system under test, so it will not be test-driven (<a href="http://blog.ploeh.dk/2013/04/02/why-trust-tests/" target="_blank">but we can trust it anyway</a>).<strong> The first test looks like this:</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="csharp" style="font-family:monospace;"> <span style="color: #008000;">&#91;</span>Fact<span style="color: #008000;">&#93;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> ReleasesUnmanagedResourcesWhenFinalized<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">var</span> spy <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ResourceSpy<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    spy<span style="color: #008000;">.</span><span style="color: #0000FF;">MimicFinalizer</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    spy<span style="color: #008000;">.</span><span style="color: #0000FF;">UnmanagedResourcesHaveBeenReleased</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Should</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">BeTrue</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p><strong>To make it compile</strong> we add:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="csharp" style="font-family:monospace;"> <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> ResourceSpy <span style="color: #008000;">:</span> ResourceOwner
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> MimicFinalizer<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#123;</span><span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">bool</span> UnmanagedResourcesHaveBeenReleased
    <span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">get</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">var</span> referencedString <span style="color: #008000;">=</span> Marshal<span style="color: #008000;">.</span><span style="color: #0000FF;">PtrToStringAuto</span><span style="color: #008000;">&#40;</span>AnUnmanagedResource<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF; font-weight: bold;">return</span> referencedString <span style="color: #008000;">!=</span> <span style="color: #666666;">&quot;Foo&quot;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p><strong>The test fails</strong>. To make it pass we release the unmanaged resources &#8211; we call FreeCoTaskMem as advised <a href="http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.stringtocotaskmemauto(v=vs.110).aspx" target="_blank">here</a>:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> ResourceSpy <span style="color: #008000;">:</span> ResourceOwner
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> MimicFinalizer<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        Marshal<span style="color: #008000;">.</span><span style="color: #0000FF;">FreeCoTaskMem</span><span style="color: #008000;">&#40;</span>AnUnmanagedResource<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">...</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>&#8230; and synchronize the Finalizer:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> ResourceOwner
<span style="color: #008000;">&#123;</span>
    <span style="color: #008000;">...</span>
    ~ResourceOwner<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        Marshal<span style="color: #008000;">.</span><span style="color: #0000FF;">FreeCoTaskMem</span><span style="color: #008000;">&#40;</span>AnUnmanagedResource<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>Now <strong>the test passes, but then the test suite crashes!</strong> The reason is that FreeCoTaskMem is being called twice &#8211; once during the test by MimicFinalizer and then when the GC calls the actual finalizer. In the real world the finalizer only ever gets called once so this doesn&#8217;t need to be handled by the ResourceOwner, rather we suppress the finalizer at the end of the test:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&#91;</span>Fact<span style="color: #008000;">&#93;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> ReleasesUnmanagedResourcesWhenFinalized<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">var</span> spy <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ResourceSpy<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    spy<span style="color: #008000;">.</span><span style="color: #0000FF;">MimicFinalizer</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    spy<span style="color: #008000;">.</span><span style="color: #0000FF;">UnmanagedResourcesHaveBeenReleased</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Should</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">BeTrue</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    GC<span style="color: #008000;">.</span><span style="color: #0000FF;">SuppressFinalize</span><span style="color: #008000;">&#40;</span>spy<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p><strong>The test passes and the test suite does not crash.</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ambersolutions.com.au/dburstin/index.php/2014/02/03/growing-idisposable-guided-by-tests/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
