<?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>Quantum Bit Designs &#187; C#</title>
	<atom:link href="http://blog.quantumbitdesigns.com/category/csharp/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.quantumbitdesigns.com</link>
	<description>Multithreading, WPF, .NET and Software Designs</description>
	<lastBuildDate>Tue, 26 Jan 2010 15:17:04 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>A Thread-Safe IDisposable Base Class</title>
		<link>http://blog.quantumbitdesigns.com/2008/07/22/a-thread-safe-idisposable-base-class/</link>
		<comments>http://blog.quantumbitdesigns.com/2008/07/22/a-thread-safe-idisposable-base-class/#comments</comments>
		<pubDate>Wed, 23 Jul 2008 03:47:49 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Threadsafety]]></category>

		<guid isPermaLink="false">http://blog.quantumbitdesigns.com/?p=35</guid>
		<description><![CDATA[Davy Brion is in the same situation as me. Every time we need to implement IDisposable (rarely) we have to look up the recommended pattern. Therefore he came up with an abstract base class that provides the proper plumbing and method signatures. All it takes is deriving from this utility class and overriding the DisposeManagedResources() [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://davybrion.com/blog">Davy Brion</a> is in the same situation as me. Every time we need to implement IDisposable (rarely) we have to look up the recommended pattern. Therefore he came up with an <a href="http://davybrion.com/blog/2008/06/disposing-of-the-idisposable-implementation/">abstract base class</a> that provides the proper plumbing and method signatures. All it takes is deriving from this utility class and overriding the DisposeManagedResources() method, and you have your IDisposable class. Obviously deriving from a utility class does not fit every scenario, but it works great for most of my needs.</p>
<p>I liked the idea so much that I decided to take it a bit further and make it &#8216;Thread-Safe&#8217;. In other words, any thread can call Dispose() on an object that derives from the following ManagedDisposable class, and the dispose plumbing will only execute once. The class is not actually thread-safe</p>
<p><strong>The ManagedDisposable Implementation:</strong></p>
<p style="margin: 0px">    <span style="color: blue">public</span> <span style="color: blue">abstract</span> <span style="color: blue">class</span> <span style="color: #2b91af">ManagedDisposable</span> : <span style="color: #2b91af">IDisposable</span></p>
<p style="margin: 0px">    {</p>
<p style="margin: 0px">        <span style="color: blue">private</span> <span style="color: blue">int</span> _disposed;</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">        <span style="color: blue">protected</span> ManagedDisposable()</p>
<p style="margin: 0px">        {</p>
<p style="margin: 0px">            <span style="color: blue">this</span>._disposed = 0;</p>
<p style="margin: 0px">        }</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">        <span style="color: blue">public</span> <span style="color: blue">bool</span> IsDisposed</p>
<p style="margin: 0px">        {</p>
<p style="margin: 0px">            <span style="color: blue">get</span></p>
<p style="margin: 0px">            {</p>
<p style="margin: 0px">                <span style="color: blue">return</span> <span style="color: blue">this</span>._disposed == 1;</p>
<p style="margin: 0px">            }</p>
<p style="margin: 0px">        }</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">        <span style="color: blue">public</span> <span style="color: blue">void</span> Dispose()</p>
<p style="margin: 0px">        {</p>
<p style="margin: 0px">            Dispose(<span style="color: blue">true</span>);</p>
<p style="margin: 0px">            <span style="color: #2b91af">GC</span>.SuppressFinalize(<span style="color: blue">this</span>);</p>
<p style="margin: 0px">        }</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">        <span style="color: blue">protected</span> <span style="color: blue">virtual</span> <span style="color: blue">void</span> Dispose(<span style="color: blue">bool</span> disposing)</p>
<p style="margin: 0px">        {</p>
<p style="margin: 0px">            <span style="color: blue">if</span> (<span style="color: #2b91af">Interlocked</span>.CompareExchange(<span style="color: blue">ref</span> <span style="color: blue">this</span>._disposed, 1, 0) == 0)</p>
<p style="margin: 0px">            {</p>
<p style="margin: 0px">                <span style="color: blue">if</span> (disposing)</p>
<p style="margin: 0px">                {</p>
<p style="margin: 0px">                    DisposeManagedResources();</p>
<p style="margin: 0px">                }</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">                DisposeUnmanagedResources();</p>
<p style="margin: 0px">            }</p>
<p style="margin: 0px">        }</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">        <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;summary&gt;</span></p>
<p style="margin: 0px">        <span style="color: gray">///</span><span style="color: green"> Helper method so subclasses can easily throw if disposed</span></p>
<p style="margin: 0px">        <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;/summary&gt;</span></p>
<p style="margin: 0px">        <span style="color: blue">protected</span> <span style="color: blue">void</span> ThrowIfDisposed()</p>
<p style="margin: 0px">        {</p>
<p style="margin: 0px">            <span style="color: blue">if</span> (<span style="color: blue">this</span>.IsDisposed == <span style="color: blue">true</span>)</p>
<p style="margin: 0px">            {</p>
<p style="margin: 0px">                <span style="color: blue">throw</span> <span style="color: blue">new</span> <span style="color: #2b91af">ObjectDisposedException</span>(<span style="color: blue">this</span>.GetType().FullName);</p>
<p style="margin: 0px">            }</p>
<p style="margin: 0px">        }</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">        <span style="color: blue">protected</span> <span style="color: blue">virtual</span> <span style="color: blue">void</span> DisposeManagedResources()</p>
<p style="margin: 0px">        {</p>
<p style="margin: 0px">        }</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">        <span style="color: blue">protected</span> <span style="color: blue">virtual</span> <span style="color: blue">void</span> DisposeUnmanagedResources()</p>
<p style="margin: 0px">        {</p>
<p style="margin: 0px">        }</p>
<p style="margin: 0px">    }</p>
<p><!--EndFragment--></p>
<p style="margin: 0px"><strong>Derived Class Example:</strong></p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">    <span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">MyThreadingObject</span> : <span style="color: #2b91af">ManagedDisposable</span></p>
<p style="margin: 0px">    {</p>
<p style="margin: 0px">        <span style="color: blue">private</span> <span style="color: #2b91af">SharedResource</span> _sharedResource;</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">        <span style="color: blue">public</span> MyThreadingObject()</p>
<p style="margin: 0px">        {</p>
<p style="margin: 0px">        }</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">        <span style="color: blue">public</span> <span style="color: blue">void</span> Start()</p>
<p style="margin: 0px">        {</p>
<p style="margin: 0px">            <span style="color: #2b91af">Thread</span> thread = <span style="color: blue">new</span> <span style="color: #2b91af">Thread</span>(ThreadMethod);</p>
<p style="margin: 0px">            thread.Start();</p>
<p style="margin: 0px">        }</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">        <span style="color: blue">private</span> <span style="color: blue">void</span> ThreadMethod()</p>
<p style="margin: 0px">        {</p>
<p style="margin: 0px">            <span style="color: blue">this</span>._sharedResource = <span style="color: blue">new</span> <span style="color: #2b91af">SharedResource</span>();</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">            <span style="color: blue">for</span> (<span style="color: blue">int</span> i = 0; i &lt; 10; ++i)</p>
<p style="margin: 0px">            {</p>
<p style="margin: 0px">                <span style="color: #2b91af">SharedResource</span> sharedResource = <span style="color: blue">this</span>._sharedResource;</p>
<p style="margin: 0px">                <span style="color: blue">if</span> (sharedResource != <span style="color: blue">null</span>)</p>
<p style="margin: 0px">                {</p>
<p style="margin: 0px">                    <span style="color: blue">lock</span> (sharedResource)</p>
<p style="margin: 0px">                    {</p>
<p style="margin: 0px">                        <span style="color: green">//do some work</span></p>
<p style="margin: 0px">                        <span style="color: green">//sharedResource.Process();</span></p>
<p style="margin: 0px">                    }</p>
<p style="margin: 0px">                }</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">                <span style="color: #2b91af">Thread</span>.Sleep(1000); <span style="color: green">//do some other work</span></p>
<p style="margin: 0px">            }</p>
<p style="margin: 0px">        }</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">        <span style="color: blue">protected</span> <span style="color: blue">override</span> <span style="color: blue">void</span> DisposeManagedResources()</p>
<p style="margin: 0px">        {</p>
<p style="margin: 0px">            <span style="color: #2b91af">SharedResource</span> sharedResource = <span style="color: blue">this</span>._sharedResource;</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">            <span style="color: blue">if</span> (sharedResource != <span style="color: blue">null</span>)</p>
<p style="margin: 0px">            {</p>
<p style="margin: 0px">                <span style="color: blue">lock</span> (sharedResource)</p>
<p style="margin: 0px">                {</p>
<p style="margin: 0px">                    sharedResource.Dispose();</p>
<p style="margin: 0px">                    <span style="color: blue">this</span>._sharedResource = <span style="color: blue">null</span>;</p>
<p style="margin: 0px">                }</p>
<p style="margin: 0px">            }</p>
<p style="margin: 0px">        }</p>
<p style="margin: 0px">    }</p>
<p>Notice how there is another element to making the implementation thread-safe. Derived classes still need to protect access to their shared resource(s) via a lock. In the case above, a lock is acquired each time the SharedResource is accessed. If such a lock did not exist, then a race condition could exist where the DisposeManagedResources() is called from another thread (disposing and setting the _sharedResource to null) while the ThreadMethod() attempts to use the resource.</p>
<p>Some may also have noticed how there is no finalizer method in the ManagedDisposable. This is because there are significant costs associated with finalization. If a finalizer is needed, use this class instead:</p>
<p><strong>UnManagedDisposable Implementation</strong></p>
<p style="margin: 0px">    <span style="color: blue">public</span> <span style="color: blue">abstract</span> <span style="color: blue">class</span> <span style="color: #2b91af">UnManagedDisposable</span> : <span style="color: #2b91af">ManagedDisposable</span></p>
<p style="margin: 0px">    {</p>
<p style="margin: 0px">        <span style="color: green">// Use C# destructor syntax for finalization code. </span></p>
<p style="margin: 0px">        <span style="color: green">// This destructor will run only if the Dispose method </span></p>
<p style="margin: 0px">        <span style="color: green">// does not get called. </span></p>
<p style="margin: 0px">        <span style="color: green">// It gives your base class the opportunity to finalize. </span></p>
<p style="margin: 0px">        <span style="color: green">// Do not provide destructors in types derived from this class. </span></p>
<p style="margin: 0px">        ~UnManagedDisposable()</p>
<p style="margin: 0px">        {</p>
<p style="margin: 0px">            Dispose(<span style="color: blue">false</span>);</p>
<p style="margin: 0px">        }</p>
<p style="margin: 0px">    }</p>
<p><!--EndFragment-->Ultimately if you are using unmanaged resources you can still use the first implementation, it just means the developer is completely responsible for calling the Dispose() method to release both managed and unmanaged resources. Otherwise the unmanaged resources will be leaked. If the second class is used, then even if a developer does not call Dispose() the destructor will eventually be called [Dispose(false) which will call DisposeUnmanagedResources()] by the garbage collector. A quick performance test indicated that ManagedDisposable is 5 times faster than UnManagedDisposable (when Dispose is not called).</p>
<p>An example of something that would ideally implement the UnManagedDisposable is the .NET Font class. If you use fonts and do not call Dispose(), the garbage collector will clean up after you eventually and free the unmanaged font resources. Really fonts should be disposed once they are no longer in use to immediately free these unmanaged resources, but the truth is thousands of developers and components do not always follow this suggestion.</p>
<p>If you don&#8217;t like two classes, just copy thr destructor code into the ManagedDisposable (and perhaps give it a better name).</p>
<p><strong>Resources</strong></p>
<ul>
<li><a href="http://www.bluebytesoftware.com/blog/2008/02/18/IDisposableFinalizationAndConcurrency.aspx">IDisposable, finalization, and concurrency </a></li>
<li><a href="http://www.bluebytesoftware.com/blog/2005/04/08/DGUpdateDisposeFinalizationAndResourceManagement.aspx">DG Update: Dispose, Finalization, and Resource Management</a></li>
<li><a href="http://blogs.msdn.com/cbrumme/archive/2004/02/20/77460.aspx">Finalization</a> (old)</li>
<li><a href="http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx">Implementing a Dispose Method</a></li>
<li><a href="http://www.devx.com/dotnet/Article/33167/1954">When and how to Use Dispose and Finalize in C#</a></li>
</ul>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fblog.quantumbitdesigns.com%2f2008%2f07%2f10%2fa-thread-safe-idisposable-base-class%2f"><img border="0" src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fblog.quantumbitdesigns.com%2f2008%2f07%2f10%2fa-thread-safe-idisposable-base-class%2f" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.quantumbitdesigns.com/2008/07/22/a-thread-safe-idisposable-base-class/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
