<?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>The Inquisitive Coder - Davy Brion&#039;s Blog &#187; Memory Management</title>
	<atom:link href="http://davybrion.com/blog/category/memory-management/feed/" rel="self" type="application/rss+xml" />
	<link>http://davybrion.com/blog</link>
	<description>Trying to walk that thin line between intelligence and ignorance</description>
	<lastBuildDate>Thu, 29 Jul 2010 20:51:03 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Avoiding Memory Leaks With NServiceBus And Your Own Castle Windsor Instance</title>
		<link>http://davybrion.com/blog/2010/02/avoiding-memory-leaks-with-nservicebus-and-your-own-castle-windsor-instance/</link>
		<comments>http://davybrion.com/blog/2010/02/avoiding-memory-leaks-with-nservicebus-and-your-own-castle-windsor-instance/#comments</comments>
		<pubDate>Fri, 19 Feb 2010 09:42:55 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[Castle Windsor]]></category>
		<category><![CDATA[Memory Management]]></category>
		<category><![CDATA[nservicebus]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=2268</guid>
		<description><![CDATA[If you’re using NServiceBus together with your own instance of Castle Windsor, there is one thing you really need to look out for.&#160; NServiceBus was originally developed with Spring.NET as its IoC container, but it’s been changed to support multiple containers in a similar manner as Agatha does it.&#160; Agatha however, was originally developed with [...]]]></description>
			<content:encoded><![CDATA[<p>If you’re using NServiceBus together with your own instance of Castle Windsor, there is one thing you really need to look out for.&#160; NServiceBus was originally developed with Spring.NET as its IoC container, but it’s been changed to support multiple containers in a similar manner as <a href="http://davybrion.com/blog/2009/11/integrating-your-ioc-container-with-agatha/" target="_blank">Agatha does it</a>.&#160; Agatha however, was originally developed with Castle Windsor as its IoC container, and as such is well aware of Windsor’s <a href="http://davybrion.com/blog/2008/12/the-importance-of-releasing-your-components-through-windsor/" target="_blank">need to explicitly release resolved components</a>.&#160;&#160; NServiceBus unfortunately was <a href="http://tech.groups.yahoo.com/group/nservicebus/message/5376" target="_blank">not aware of this need</a>, and a workaround that they have introduced is to set Windsor’s ReleasePolicy to the NoTrackingReleasePolicy (which doesn’t hold any instances in memory, but doesn’t provide any cleanup either) if you configure NServiceBus to use <em>its own instance of </em>Castle Windsor.&#160; However, if you’re integrating NServiceBus into a project that is already using Castle Windsor, then you probably want NServiceBus to use <em>your instance</em> of Castle Windsor.</p>
<p>And that is when problems might appear.&#160; If you’re using Castle Windsor with the default ReleasePolicy (which is the LifecycledComponentsReleasePolicy) then each resolved transient instance will be stored in memory by that policy until the instance is explicitly released.&#160; The benefit of this policy is that the container can automatically dispose any disposable transient dependency of a resolved component.&#160; In my case, i’ve come to rely on that feature to achieve deterministic disposal behavior throughout my code base.&#160; </p>
<p>Now, when you configure NServiceBus and pass it your instance of Castle Windsor, it obviously doesn’t change the ReleasePolicy like it does when it creates its own instance of Castle Windsor.&#160;&#160; This is good because changing the policy of a passed in container would almost certainly have a huge behavioral implication for the application and such an action would be unacceptable when integrating a new framework into your project.&#160;&#160; But since NServiceBus doesn’t have the notion of needing to release resolved components, every single transient instance it resolves through <em>your</em> container will be stored in memory until the application’s process is terminated.&#160; Which means that you’ll leak instances of the following types <em>for each message</em> that your system needs to handle:</p>
<ul>
<li>NServiceBus.Grid.MessageHandlers.GridInterceptingMessageHandler </li>
<li>NServiceBus.Sagas.Impl.SagaMessageHandler </li>
<li>Your own MessageHandlers (and their transient dependencies as well) </li>
</ul>
<p>If your MessageHandlers don’t have dependencies (highly unlikely if you’re already using an IOC container) then you’d still have 3 leaking instances per incoming message.&#160; Add the number of transient dependencies of any handler to that and the number of leaking instances can increase dramatically.</p>
<p>First of all, if you do not depend on Windsor’s default ReleasePolicy’s behavior, then the easiest way to avoid this problem is definitely to set the container’s ReleasePolicy to the NoTrackingReleasePolicy like NServiceBus does itself when it’s configuring itself with a new instance of the container.</p>
<p>If you do depend on it, and you don’t want leaking instances that hang around forever, then the approach listed below is one way to solve this problem.&#160; There are probably other solutions available, and while the approach listed below can definitely be considered to be a HACK, i do think it’s the best solution to this particular problem.</p>
<p>Because we don’t want to change anything about the way that we’re already using the container, we just need to make sure that NServiceBus’ usage of the container doesn’t conflict with ours.&#160; That basically means that we need to make sure that the components that it resolves should not be tracked by the container.&#160;&#160; There are 2 kinds of components that NServiceBus will resolve during normal operation:</p>
<ol>
<li>Its own components that it needs to implement the features it offers you </li>
<li>Your message handlers that you need to handle incoming messages </li>
</ol>
<p>The first category is easy to exclude from Windsor’s tracking behavior.&#160; We can simply create our own ReleasePolicy which extends the default ReleasePolicy, and make sure that any instances of an NServiceBus-type are no longer tracked by the container:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">MyReleasePolicy</span> : Castle.MicroKernel.Releasers.<span style="color: #2b91af">LifecycledComponentsReleasePolicy</span></p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: blue">void</span> Track(<span style="color: blue">object</span> instance, Castle.MicroKernel.<span style="color: #2b91af">Burden</span> burden)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (!instance.GetType().FullName.StartsWith(<span style="color: #a31515">&quot;NServiceBus&quot;</span>))</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">base</span>.Track(instance, burden);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
</p></div>
<p>&#160;</p>
<p>Then you need to set this release policy somewhere in your application’s startup routine:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">IoC</span>.Container.Kernel.ReleasePolicy = <span style="color: blue">new</span> <span style="color: #2b91af">MyReleasePolicy</span>();</p>
</p></div>
<p>&#160;</p>
<p>(in this case, IoC.Container returns an IWindsorContainer instance)</p>
<p>This will make sure that no instances of NServiceBus-types will ever leak in the container.&#160; But now we still have to deal with our message handlers.&#160; The solution to making sure they are not disposed is not the cleanest out there but hey, it works.&#160; I basically introduced a base class that all my message handlers will need to inherit from, with the following implementation in the Handle method:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">abstract</span> <span style="color: blue">class</span> <span style="color: #2b91af">MessageHandler</span>&lt;TMessage&gt; : <span style="color: #2b91af">IMessageHandler</span>&lt;TMessage&gt; <span style="color: blue">where</span> TMessage : <span style="color: #2b91af">IMessage</span></p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">void</span> Handle(TMessage message)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">try</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Process(message);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">finally</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: green">// ugly as hell, but we need this until NSB releases its resolved components</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">IoC</span>.Container.Release(<span style="color: blue">this</span>);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">protected</span> <span style="color: blue">abstract</span> <span style="color: blue">void</span> Process(TMessage message);</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
</p></div>
<p>&#160;</p>
<p>Uh oh… i just felt a great disturbance in the Force, as if tens of voices suddenly cried out in terror about my direct usage of the IoC container in a component!</p>
<p>Conceptually, this is wrong on many levels.&#160; Then again, this makes sure that the message handlers (and their dependencies) that are resolved by NServiceBus will always be guaranteed to be released by the comtainer.&#160; It might not be nice, but it avoids the memory leak and it doesn’t force me to change <em>my other code</em>.</p>
<p>And once NServiceBus is modified to release the components it resolves (if it’s ever modified that is…) i only need to get rid of my custom policy and the try/finally block.&#160; Unfortunately, my existing message handlers will then all implement the Process method instead of the Handle method but that is quickly fixed with a simple rename-refactoring.</p>
<p>Even though this is a pretty big hack (IMHO), at least its impact on the code is minimal… it will be easy to get rid of once the real problem is solved in NSB, and there are no real downsides to this that i can think of at the moment. </p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2010/02/avoiding-memory-leaks-with-nservicebus-and-your-own-castle-windsor-instance/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Can You Come Up With A WHY Comment For This Code?</title>
		<link>http://davybrion.com/blog/2010/02/can-you-come-up-with-a-why-comment-for-this-code/</link>
		<comments>http://davybrion.com/blog/2010/02/can-you-come-up-with-a-why-comment-for-this-code/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 16:26:18 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[Memory Management]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/2010/02/can-you-come-up-with-a-why-comment-for-this-code/</guid>
		<description><![CDATA[I just had to write the following code: &#160;&#160;&#160; public class MyReleasePolicy : Castle.MicroKernel.Releasers.LifecycledComponentsReleasePolicy &#160;&#160;&#160; { &#160;&#160;&#160;&#160;&#160;&#160;&#160; public override void Track(object instance, Castle.MicroKernel.Burden burden) &#160;&#160;&#160;&#160;&#160;&#160;&#160; { &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (!instance.GetType().FullName.StartsWith(&#34;NServiceBus&#34;)) &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; { &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; base.Track(instance, burden); &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; } &#160;&#160;&#160;&#160;&#160;&#160;&#160; } &#160;&#160;&#160; } &#160; and then this: &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; IoC.Container.Kernel.ReleasePolicy = new MyReleasePolicy(); &#160; to make a problem go [...]]]></description>
			<content:encoded><![CDATA[<p>I just had to write the following code:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">MyReleasePolicy</span> : Castle.MicroKernel.Releasers.<span style="color: #2b91af">LifecycledComponentsReleasePolicy</span></p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: blue">void</span> Track(<span style="color: blue">object</span> instance, Castle.MicroKernel.<span style="color: #2b91af">Burden</span> burden)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (!instance.GetType().FullName.StartsWith(<span style="color: #a31515">&quot;NServiceBus&quot;</span>))</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">base</span>.Track(instance, burden);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
</p></div>
<p>&#160;</p>
<p>and then this:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">IoC</span>.Container.Kernel.ReleasePolicy = <span style="color: blue">new</span> <span style="color: #2b91af">MyReleasePolicy</span>();</p>
</p></div>
<p>&#160;</p>
<p>to make a problem go away.</p>
<p>Can you come up with a WHY comment? (the category of this post is another hint)</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2010/02/can-you-come-up-with-a-why-comment-for-this-code/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Event Subscribtion And Memory Leaks (Yet Again)</title>
		<link>http://davybrion.com/blog/2009/09/event-subscribtion-and-memory-leaks-yet-again/</link>
		<comments>http://davybrion.com/blog/2009/09/event-subscribtion-and-memory-leaks-yet-again/#comments</comments>
		<pubDate>Sat, 12 Sep 2009 16:32:35 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[Memory Management]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1677</guid>
		<description><![CDATA[Just read the following post by Fabrice Marguerie about forcing event unsubscription to avoid the typical memory leaks that occur frequently with event handlers. Unfortunately, the solution in his post will in most cases be useless. First of all, consider the following 2 classes: .cf { font-family: Consolas; font-size: 9pt; color: black; background: white; } [...]]]></description>
			<content:encoded><![CDATA[<p>Just read the following <a href="http://weblogs.asp.net/fmarguerie/archive/2009/09/09/forcing-event-unsubscription.aspx">post</a> by Fabrice Marguerie about forcing event unsubscription to avoid the typical memory leaks that occur frequently with event handlers.  Unfortunately, the solution in his post will in most cases be useless.</p>
<p>First of all, consider the following 2 classes:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #2b91af; }
.cb3 { color: #a31515; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">class</span> <span class="cb2">Publisher</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">event</span> <span class="cb2">EventHandler</span>&lt;<span class="cb2">EventArgs</span>&gt; MyEvent = <span class="cb1">delegate</span> { };</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">void</span> RaiseEvent()</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; MyEvent(<span class="cb1">this</span>, <span class="cb2">EventArgs</span>.Empty);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">class</span> <span class="cb2">Subscriber</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb1">static</span> <span class="cb1">int</span> counter;</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb1">int</span> currentInstanceCount;</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> Subscriber(<span class="cb2">Publisher</span> publisher)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; currentInstanceCount = ++counter;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; publisher.MyEvent += producer_MyEvent;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">void</span> producer_MyEvent(<span class="cb1">object</span> sender, <span class="cb2">EventArgs</span> e)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">Console</span>.WriteLine(<span class="cb1">string</span>.Format(<span class="cb3">&quot;Instance {0} is handling event...&quot;</span>, currentInstanceCount));</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>Pretty simple&#8230; the Publisher publishes the MyEvent event, and the Subscriber subscribes to the event when an instance is created.  As you should already know, <strong>whenever the publisher of an event has a longer lifecycle than its subscibers, subscribers must explicitly unsubscribe from the event to prevent instances of the subscribers to remain in memory instead of being garbage collected</strong>.</p>
<p>The following simple example illustrates the problem:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #2b91af; }
.cb3 { color: #a31515; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">var</span> publisher = <span class="cb1">new</span> <span class="cb2">Publisher</span>();</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">var</span> subscriber1 = <span class="cb1">new</span> <span class="cb2">Subscriber</span>(publisher);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">var</span> subscriber2 = <span class="cb1">new</span> <span class="cb2">Subscriber</span>(publisher);</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">Console</span>.WriteLine(<span class="cb3">&quot;triggering event for the first time... both subscribers should respond&quot;</span>);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; publisher.RaiseEvent();</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; subscriber1 = <span class="cb1">null</span>;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">GC</span>.Collect();</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">Console</span>.WriteLine(<span class="cb3">&quot;triggering event for the second time... hopefully, the first subscriber has been collected&quot;</span>);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; publisher.RaiseEvent();</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; subscriber2 = <span class="cb1">null</span>;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">GC</span>.Collect();</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">Console</span>.WriteLine(<span class="cb3">&quot;triggering event for the third time... hopefully, both subscribers have been collected&quot;</span>);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; publisher.RaiseEvent();</p>
</div>
<p></code></p>
<p>This will produce the following console output:</p>
<p>triggering event for the first time&#8230; both subscribers should respond<br />
Instance 1 is handling event&#8230;<br />
Instance 2 is handling event&#8230;<br />
triggering event for the second time&#8230; hopefully, the first subscriber has been collected<br />
Instance 1 is handling event&#8230;<br />
Instance 2 is handling event&#8230;<br />
triggering event for the third time&#8230; hopefully, both subscribers have been collected<br />
Instance 1 is handling event&#8230;<br />
Instance 2 is handling event&#8230;</p>
<p>Obviously, both subscriber instances remained in memory even though we no longer had references to those instances and they should&#8217;ve been collected by the garbage collector.  For those of you who don&#8217;t know what&#8217;s going on: an event handler will internally keep a list of references to all the objects that subscribed to the event.  This means that it is only normal that the Publisher is actually keeping all of the Subscriber instances &#8216;live&#8217; because it keeps references to it.  That means that the garbage collector will never collect these instances <strong>until the Producer is eligible for garbage collection</strong>.</p>
<p>Now, Fabrice&#8217;s proposed solution is to change the Producer to this:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #2b91af; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">class</span> <span class="cb2">Publisher</span> : <span class="cb2">IDisposable</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">event</span> <span class="cb2">EventHandler</span>&lt;<span class="cb2">EventArgs</span>&gt; MyEvent = <span class="cb1">delegate</span> { };</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">void</span> RaiseEvent()</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; MyEvent(<span class="cb1">this</span>, <span class="cb2">EventArgs</span>.Empty);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">void</span> Dispose()</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; MyEvent = <span class="cb1">null</span>;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>Again, memory leaks through event subscription only occur when the publisher of an event lives longer than the subscribers of an event.  Obviously, this solution will hardly help in the situation where the memory actually leaks, because the publisher will not be disposed of until it is no longer needed.  Which means that the Producer will still keep all instances from no-longer-needed subscribers in memory.</p>
<p>The only way to avoid this problem is to explicitly unsubscribe each subscriber from the event.  Which means that you should implement IDisposable on the Subscriber:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #2b91af; }
.cb3 { color: #a31515; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">class</span> <span class="cb2">Subscriber</span> : <span class="cb2">IDisposable</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb1">static</span> <span class="cb1">int</span> counter;</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb1">int</span> currentInstanceCount;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb2">Publisher</span> publisher;</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> Subscriber(<span class="cb2">Publisher</span> publisher)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; currentInstanceCount = ++counter;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">this</span>.publisher = publisher;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; publisher.MyEvent += producer_MyEvent;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">void</span> producer_MyEvent(<span class="cb1">object</span> sender, <span class="cb2">EventArgs</span> e)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">Console</span>.WriteLine(<span class="cb1">string</span>.Format(<span class="cb3">&quot;Instance {0} is handling event...&quot;</span>, currentInstanceCount));</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">void</span> Dispose()</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; publisher.MyEvent -= producer_MyEvent;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>That&#8217;s not enough though&#8230; you need to explicitly dispose these instances as well.  So the example code now looks like this:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #2b91af; }
.cb3 { color: #a31515; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">var</span> publisher = <span class="cb1">new</span> <span class="cb2">Publisher</span>();</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">var</span> subscriber1 = <span class="cb1">new</span> <span class="cb2">Subscriber</span>(publisher);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">var</span> subscriber2 = <span class="cb1">new</span> <span class="cb2">Subscriber</span>(publisher);</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">Console</span>.WriteLine(<span class="cb3">&quot;triggering event for the first time... both subscribers should respond&quot;</span>);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; publisher.RaiseEvent();</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; subscriber1.Dispose();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; subscriber1 = <span class="cb1">null</span>;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">GC</span>.Collect();</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">Console</span>.WriteLine(<span class="cb3">&quot;triggering event for the second time... hopefully, the first subscriber has been collected&quot;</span>);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; publisher.RaiseEvent();</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; subscriber2.Dispose();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; subscriber2 = <span class="cb1">null</span>;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">GC</span>.Collect();</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">Console</span>.WriteLine(<span class="cb3">&quot;triggering event for the third time... hopefully, both subscribers have been collected&quot;</span>);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; publisher.RaiseEvent();</p>
</div>
<p></code></p>
<p>And the output of this code is now correct:</p>
<p>triggering event for the first time&#8230; both subscribers should respond<br />
Instance 1 is handling event&#8230;<br />
Instance 2 is handling event&#8230;<br />
triggering event for the second time&#8230; hopefully, the first subscriber has been collected<br />
Instance 2 is handling event&#8230;<br />
triggering event for the third time&#8230; hopefully, both subscribers have been collected</p>
<p>To summarize:</p>
<ul>
<li>
<p>If a producer will stay alive longer than the subscriber, then it will keep the subscribers in memory until the publisher gets garbage collected</p>
</li>
<li>
<p>Your subscribers should explicitly unsubscribe from events from publishers, unless you know that the lifetime of both the subscriber or the publisher is either identical, or that the publisher has a shorter lifetime than the subscriber.  You should preferably unsubscribe from these events in a Dispose method and your subscriber should implement IDisposable.</p>
</li>
<li>
<p>Always call the Dispose method on subscribers that implement IDisposable. Otherwise, you&#8217;ll still leak instances of the subscribers.</p>
</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/09/event-subscribtion-and-memory-leaks-yet-again/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Finding Memory Leaks In Silverlight With WinDbg</title>
		<link>http://davybrion.com/blog/2009/08/finding-memory-leaks-in-silverlight-with-windbg/</link>
		<comments>http://davybrion.com/blog/2009/08/finding-memory-leaks-in-silverlight-with-windbg/#comments</comments>
		<pubDate>Sat, 08 Aug 2009 17:00:15 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[Memory Management]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1496</guid>
		<description><![CDATA[As i mentioned in a previous post, you can attach WinDbg to a browser to find memory leaks in your Silverlight applications. I figured it would be a good idea to write down how this process works, since i always end up having to look it up again whenever i need to do this. I [...]]]></description>
			<content:encoded><![CDATA[<p>As i mentioned in a <a href="http://davybrion.com/blog/2009/08/tracking-dangling-object-references-in-silverlight/">previous post</a>, you can attach WinDbg to a browser to find memory leaks in your Silverlight applications.  I figured it would be a good idea to write down how this process works, since i always end up having to look it up again whenever i need to do this.</p>
<p>I wrote a very simple Silverlight application which has a rather typical memory leak. Here&#8217;s the actual code:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #2b91af; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">event</span> <span class="cb2">EventHandler</span>&lt;<span class="cb2">MyEventArgs</span>&gt; MyEvent = <span class="cb1">delegate</span> { };</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb1">void</span> CreateNewViewButton_OnClick(<span class="cb1">object</span> sender, <span class="cb2">RoutedEventArgs</span> e)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; ViewContainer.Children.Clear();</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">var</span> newView = <span class="cb1">new</span> <span class="cb2">MyView</span>();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; MyEvent += newView.EventHandler;</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; ViewContainer.Children.Add(newView);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>For some of you, the memory leak is already very clear.  Like i said, it&#8217;s a very simple example <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>Let&#8217;s go through the process of finding and fixing the memory leak using WinDbg. First of all, download Debugging Tools For Windows (which contains the WinDbg executable) <a href="http://www.microsoft.com/whdc/devtools/debugging/installx86.mspx">here</a> and install it.</p>
<p>Then we start our application in Internet Explorer (for some reason i can&#8217;t use WinDbg to inspect the managed memory heap with Firefox, so i just use Internet Explorer for this stuff) and use it.  In the case of my example, that means clicking the button which creates a new view a couple of times.</p>
<p>Open WinDbg.exe and select the &#8216;Attach to a Process&#8217; menu item in the &#8216;File&#8217; menu and select the iexplore.exe process.</p>
<p>Then you need to load the correct version of sos.dll:</p>
<p>
<img src="http://davybrion.com/blog/wp-content/uploads/2009/08/step1.png" alt="step1" title="step1" width="606" height="15" class="size-full wp-image-1498" />
</p>
<p>After that we can see which types of our MySilverlightApplication namespace are present in the managed heap, including how many instances of them:</p>
<p>
<img src="http://davybrion.com/blog/wp-content/uploads/2009/08/step2.png" alt="step2" title="step2" width="952" height="122" class="size-full wp-image-1499" />
</p>
<p>As you can see, there are 13 instances of our MyView type present in the heap.  Using the value in the MT column, we can drill down further:</p>
<p>
<img src="http://davybrion.com/blog/wp-content/uploads/2009/08/step3.png" alt="step3" title="step3" width="512" height="266" class="size-full wp-image-1500" />
</p>
<p>This shows the memory address of each instance of the MyView type in the heap.  Now we can see if there are any live references to these instances:</p>
<p>
<img src="http://davybrion.com/blog/wp-content/uploads/2009/08/step4.png" alt="step4" title="step4" width="831" height="192" class="size-full wp-image-1501" />
</p>
<p>This is actually for the first address that was listed.  As you can see, it is still a reachable reference, which means it will not be collected by the garbage collector. The chain of references clearly indicates that the instance is still referenced from our event in the MainPage instance.  All of the previously listed instances show the same reference chain, so this is clearly a memory leak.  Even though we should only have one active reference of MyView at any point in time of this application, the MyEvent event on MainPage clearly keeps each instance of MyView alive. </p>
<p>The correct way to fix this is to make sure that whenever we remove an instance of MyView, we need to unsubscribe it from the MainPage&#8217;s MyEvent handler.  Always remember this rule when it comes to dealing with events: if the publisher of the event has a longer lifetime than the subscriber of the event, then you absolutely have to unsubscribe each subscriber from the event or the publisher will keep references to each subscriber (preventing them from being garbage collected) for as long as the publisher is alive.</p>
<p>Here&#8217;s the modified version of the above code which avoids the memory leak:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #2b91af; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">event</span> <span class="cb2">EventHandler</span>&lt;<span class="cb2">MyEventArgs</span>&gt; MyEvent = <span class="cb1">delegate</span> { };</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb1">void</span> CreateNewViewButton_OnClick(<span class="cb1">object</span> sender, <span class="cb2">RoutedEventArgs</span> e)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; CleanUpPreviousView();</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">var</span> newView = <span class="cb1">new</span> <span class="cb2">MyView</span>();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; MyEvent += newView.EventHandler;</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; ViewContainer.Children.Add(newView);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb1">void</span> CleanUpPreviousView()</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">if</span> (ViewContainer.Children.Count &gt; 0)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">var</span> myView = ViewContainer.Children[0] <span class="cb1">as</span> <span class="cb2">MyView</span>;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">if</span> (myView != <span class="cb1">null</span>) MyEvent -= myView.EventHandler;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; ViewContainer.Children.Clear();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>Let&#8217;s see if this really fixed the memory leak.  If we fire up the application and press the button a couple of times, the application should normally only have one live reference of MyView in memory.</p>
<p>
<img src="http://davybrion.com/blog/wp-content/uploads/2009/08/step5.png" alt="step5" title="step5" width="952" height="125" class="size-full wp-image-1502" />
</p>
<p>I clicked the button 5 times, and the above output shows that there are 5 instances of MyView on the heap.  So did we fix the leak or not?  Check the output below:</p>
<p>
<img src="http://davybrion.com/blog/wp-content/uploads/2009/08/step6.png" alt="step6" title="step6" width="622" height="604" class="size-full wp-image-1497" />
</p>
<p>As you can see, only the last instance of MyView is actively referenced somewhere.  That means that the first 4 instances are ready to be collected during the next garbage collection.  </p>
<p>One thing i don&#8217;t understand though, is that the reference chain of the last instance doesn&#8217;t mention MainPage or the event handler anymore.  But when i attached Visual Studio&#8217;s debugger to the browser instance i could clearly see that the MyEvent of MainPage indeed contained an event handler that pointed to this MyView instance.  I&#8217;m far from a WinDbg and SOS expert so i have no idea why the reference chain doesn&#8217;t reflect this.  Perhaps someone with more WinDbg and SOS knowledge can shed some light on this?</p>
<p>Either way, this approach is a pretty good way of finding memory leaks in your Silverlight code.  In a real application it&#8217;s obviously a bit more complicated to find the exact cause of a leak compared to this simple example, but it&#8217;s still pretty doable.  Just execute the !dumpheap -stat -type YourRootNameSpaceHere and look for unusually high numbers of instances of your types.  Then you can start looking at each instance to figure out what&#8217;s going on.  And for a nice list of commands that you can execute in WinDbg with SOS, be sure to check <a href="http://msdn.microsoft.com/en-us/library/bb190764.aspx">this</a> out.</p>
<p>Also, keep in mind that you can do this for every .NET process, and not just Silverlight.  Though you would need to load the sos.dll file of your particular .NET version.</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/08/finding-memory-leaks-in-silverlight-with-windbg/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Tracking Dangling Object References In Silverlight</title>
		<link>http://davybrion.com/blog/2009/08/tracking-dangling-object-references-in-silverlight/</link>
		<comments>http://davybrion.com/blog/2009/08/tracking-dangling-object-references-in-silverlight/#comments</comments>
		<pubDate>Tue, 04 Aug 2009 15:39:58 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[Memory Management]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1478</guid>
		<description><![CDATA[One of the downsides of working with a young platform like Silverlight is that the tool support isn&#8217;t quite &#8216;there&#8217; yet, particularly when it comes to profiling for performance and memory usage. And as you may or may not know, Silverlight makes it very easy to introduce memory leaks into your code. Since you can&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p>One of the downsides of working with a young platform like Silverlight is that the tool support isn&#8217;t quite &#8216;there&#8217; yet, particularly when it comes to profiling for performance and memory usage.  And as you may or may not know, Silverlight makes it very easy to introduce memory leaks into your code.  Since you can&#8217;t just attach a memory profiler to your Silverlight application, optimizing memory usage or tracking down a leak can be a real pain in the ass.</p>
<p>In the past i have resorted to grabbing a memory dump of the browser and analyzing the content of the managed heap with windbg to track down which instances where being kept in memory.  While this works, it&#8217;s pretty time consuming and can quite easily lead you down the wrong path.  One of the most important things that you want to know in this specific case is: which types are being kept in memory, and how many of them?</p>
<p>In this case, being able to query something during debugging regarding which instances are still kept alive in memory at certain times is sufficient for me.  So i came up with the following class:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 9pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">static</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">ObjectTracker</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">static</span> <span style="color: blue;">readonly</span> <span style="color: blue;">object</span> monitor = <span style="color: blue;">new</span> <span style="color: blue;">object</span>();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">static</span> <span style="color: blue;">readonly</span> <span style="color: #2b91af;">List</span>&lt;<span style="color: #2b91af;">WeakReference</span>&gt; objects = <span style="color: blue;">new</span> <span style="color: #2b91af;">List</span>&lt;<span style="color: #2b91af;">WeakReference</span>&gt;();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">static</span> <span style="color: blue;">bool</span>? shouldTrack;</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">static</span> <span style="color: blue;">void</span> Track(<span style="color: blue;">object</span> objectToTrack)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">if</span> (ShouldTrack())</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">lock</span> (monitor)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; objects.Add(<span style="color: blue;">new</span> <span style="color: #2b91af;">WeakReference</span>(objectToTrack));</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }&nbsp;&nbsp; </p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">static</span> <span style="color: blue;">bool</span> ShouldTrack()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">if</span> (shouldTrack == <span style="color: blue;">null</span>)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; shouldTrack = <span style="color: #2b91af;">Debugger</span>.IsAttached;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span> shouldTrack.Value;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">static</span> <span style="color: #2b91af;">IEnumerable</span>&lt;<span style="color: blue;">object</span>&gt; GetAllLiveTrackedObjects()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">lock</span> (monitor)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">GC</span>.Collect();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span> objects.Where(o =&gt; o.IsAlive).Select(o =&gt; o.Target);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>The idea is basically to just keep a list of WeakReferences of objects you want to track (only if a debugger is attached), and later on you can &#8216;query&#8217; the live instances through the GetAllLiveTrackedObjects method.  This method obviously performs a full garbage collect to make sure only objects that are really still alive are returned.  Again, you should almost never do a GC.Collect() manually, but in this case the method will only be called while you&#8217;re debugging.</p>
<p>Then, you strategically put the following line in the constructor of every kind of type you&#8217;d like to track:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 9pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">ObjectTracker</span>.Track(<span style="color: blue;">this</span>);</p>
</div>
<p></code></p>
<p>I have that line in the constructor of my base View class, my base Controller class and in my base Disposable class.  So now, when i want to check if there are any dangling references to instances of types that i really don&#8217;t want hanging around, i can just do something like this:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 9pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> liveObjects = <span style="color: #2b91af;">ObjectTracker</span>.GetAllLiveTrackedObjects();</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">if</span> (<span style="color: #2b91af;">Debugger</span>.IsAttached)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">Debugger</span>.Break();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>And then manually inspect the content of the liveObjects collection.  It&#8217;s far from perfect, but at least it&#8217;s an easy way to at least know which instances (that i care about) are being kept in memory.  It&#8217;ll do until we get better tool support :p</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/08/tracking-dangling-object-references-in-silverlight/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>The Joys Of Debugging ASP.NET Memory Leaks</title>
		<link>http://davybrion.com/blog/2009/04/the-joys-of-debugging-aspnet-memory-leaks/</link>
		<comments>http://davybrion.com/blog/2009/04/the-joys-of-debugging-aspnet-memory-leaks/#comments</comments>
		<pubDate>Mon, 06 Apr 2009 20:37:14 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[.NET bugs]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Memory Management]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1271</guid>
		<description><![CDATA[One of my coworkers describes a very interesting memory leak he just fixed. Be sure to read his post to get the entire story. We basically had a custom UserControl which contained (among other things) a Repeater which would render another custom UserControl. Nothing really weird there, right? The problem was that the custom UserControl [...]]]></description>
			<content:encoded><![CDATA[<p>One of my coworkers <a href="http://blog.kristofrennen.be/index.php/2009/04/how-an-aspnet-databind-can-cause-a-memory-leak/">describes</a> a very interesting memory leak he just fixed.  Be sure to read his post to get the entire story.</p>
<p>We basically had a custom UserControl which contained (among other things) a Repeater which would render another custom UserControl.  Nothing really weird there, right?  The problem was that the custom UserControl that was created by the Repeater explicitly needed to be disposed.  No problem, System.Web.UI.Control implements IDisposable so we could just override the Dispose method, perform our cleanup there and then proceed with the base Dispose implementation.  </p>
<p>Now, i&#8217;m far from an ASP.NET expert but i was under the impression that all Page and UserControl instances would always have their Dispose method called if they were created by other ASP.NET controls (containing pages or controls).  After all, what&#8217;s the point in implementing IDisposable in the base Control class if you&#8217;re not even going to guarantee proper usage of the pattern, right?</p>
<p>Well, as Kristof describes in his post, there is <a href="http://blog.kristofrennen.be/index.php/2009/04/how-an-aspnet-databind-can-cause-a-memory-leak/">at least one situation</a> where a UserControl is not disposed of, even though it was created by a Repeater.  In our case, the leak was subtle.  It took a stress test of 10 hours with a load that would be comparable to real world usage of one month to expose the leak.  A lot of people would say &#8220;oh, let&#8217;s just recycle the application pool periodically and everything is A-OK&#8221;.  But the very idea of having to recycle an application pool periodically to keep a system up and running is just a cop out to me.  Good code should not require periodic restarts.  Period.</p>
<p>I wonder how many ASP.NET WebForms applications might actually have the same (or at least similar) problem(s) like the one Kristof encountered.   If everyone keeps recycling their application pools periodically, we unfortunately may never found out.</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/04/the-joys-of-debugging-aspnet-memory-leaks/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Silverlight&#8217;s ProgressBar And Possible Memory Leaks</title>
		<link>http://davybrion.com/blog/2009/02/silverlights-progressbar-and-possible-memory-leaks/</link>
		<comments>http://davybrion.com/blog/2009/02/silverlights-progressbar-and-possible-memory-leaks/#comments</comments>
		<pubDate>Wed, 25 Feb 2009 15:42:44 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[Memory Management]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1012</guid>
		<description><![CDATA[This has got to be the weirdest memory leak i&#8217;ve ever investigated. We have this kick-ass Silverlight application, but unfortunately it suffered from very high memory usage that went up rather rapidly. So i attached windbg to the browser&#8217;s process, took a memory dump and checked out which objects were still available in the heap. [...]]]></description>
			<content:encoded><![CDATA[<p>This has got to be the weirdest memory leak i&#8217;ve ever investigated.  We have this kick-ass Silverlight application, but unfortunately it suffered from very high memory usage that went up rather rapidly.  So i attached windbg to the browser&#8217;s process, took a memory dump and checked out which objects were still available in the heap.  Much to my surprise, pretty much everything we instantiated was retained in memory and never got removed from the heap.</p>
<p>So i started looking into the usual things: making sure disposable instances where disposed of properly, that evenhandlers were unregistered properly, etc.  I went over the code and it seemed to be alright.  Stepping through the code with a debugger verified that disposables were indeed disposed of, and that all event handlers were unregistered.</p>
<p>So why was pretty much everything kept in memory?  Further research with windbg showed that every ProgressBar instance that was ever created (and we use a lot of them, basically every time we make a call to the application server) kept a reference to the UserControl it was placed on and thus, kept the UserControl and all the references it contained alive.  In our case, that includes our presentation models and obviously all of the contained child UserControls.</p>
<p>The ProgressBar is defined like this:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 9pt; color: black; background: white;">
<p style="margin: 0px;"><span style="color: blue;">&lt;</span><span style="color: #a31515;">ProgressBar</span><span style="color: red;"> Height</span><span style="color: blue;">=&quot;40&quot;</span><span style="color: red;"> Style</span><span style="color: blue;">=&quot;{</span><span style="color: #a31515;">StaticResource</span><span style="color: red;"> ourKickAssStyle</span><span style="color: blue;">}&quot;</span><span style="color: red;"> VerticalAlignment</span><span style="color: blue;">=&quot;Center&quot;</span><span style="color: red;"> Width</span><span style="color: blue;">=&quot;40&quot;</span><span style="color: red;"> IsIndeterminate</span><span style="color: blue;">=&quot;True&quot;/&gt;</span></p>
</div>
<p></code></p>
<p>The key here is the usage of the IsIndeterminate property&#8230; setting this to true causes the ProgressBar to move continuously without respecting any current Value property.  You know, basic stuff.  The thing is&#8230; if i change the definition of the ProgressBar to this:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 9pt; color: black; background: white;">
<p style="margin: 0px;"><span style="color: blue;">&lt;</span><span style="color: #a31515;">ProgressBar</span><span style="color: red;"> Height</span><span style="color: blue;">=&quot;40&quot;</span><span style="color: red;"> Style</span><span style="color: blue;">=&quot;{</span><span style="color: #a31515;">StaticResource</span><span style="color: red;"> ourKickAssStyle</span><span style="color: blue;">}&quot;</span><span style="color: red;"> VerticalAlignment</span><span style="color: blue;">=&quot;Center&quot;</span><span style="color: red;"> Width</span><span style="color: blue;">=&quot;40&quot; /&gt;</span></p>
</div>
<p></code></p>
<p>The memory leak suddenly went away <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Obviously, this isn&#8217;t a solution because the ProgressBar now doesn&#8217;t really indicate any progress and we need our kick ass custom animation to retain the coolness of the application.</p>
<p>So for some reason, when you set the ProgressBar&#8217;s IsIndeterminate property to true, it actually keeps all of its references alive even when the ProgressBar control is removed from its parent control.  Happy times.</p>
<p>We now have the following ugly method in one of our base UI classes:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 9pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">static</span> <span style="color: blue;">void</span> StopProgressBars(<span style="color: #2b91af;">DependencyObject</span> dependencyObject)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> count = <span style="color: #2b91af;">VisualTreeHelper</span>.GetChildrenCount(dependencyObject);</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">for</span> (<span style="color: blue;">int</span> i = 0; i &lt; count; i++)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> child = <span style="color: #2b91af;">VisualTreeHelper</span>.GetChild(dependencyObject, i);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">if</span> (child != <span style="color: blue;">null</span>)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> progressBar = child <span style="color: blue;">as</span> <span style="color: #2b91af;">ProgressBar</span>;</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">if</span> (progressBar != <span style="color: blue;">null</span>)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; progressBar.IsIndeterminate = <span style="color: blue;">false</span>;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; StopProgressBars(child);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/02/silverlights-progressbar-and-possible-memory-leaks/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Great Links On Using Garbage Collection Efficiently</title>
		<link>http://davybrion.com/blog/2009/01/great-links-on-using-garbage-collection-efficiently/</link>
		<comments>http://davybrion.com/blog/2009/01/great-links-on-using-garbage-collection-efficiently/#comments</comments>
		<pubDate>Sun, 11 Jan 2009 19:23:56 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[Memory Management]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=842</guid>
		<description><![CDATA[I usually try to avoid posts that merely link to other stuff, but these links are just too good: Using GC Efficiently, Part 1 Using GC Efficiently, Part 2 Using GC Efficiently, Part 3 Using GC Efficiently, Part 4]]></description>
			<content:encoded><![CDATA[<p>I usually try to avoid posts that merely link to other stuff, but these links are just too good:</p>
<ul>
<li><a href="http://blogs.msdn.com/maoni/archive/2004/06/15/156626.aspx">Using GC Efficiently, Part 1</a></li>
<li><a href="http://blogs.msdn.com/maoni/archive/2004/09/25/234273.aspx">Using GC Efficiently, Part 2</a></li>
<li><a href="http://blogs.msdn.com/maoni/archive/2004/12/19/327149.aspx">Using GC Efficiently, Part 3</a></li>
<li><a href="http://blogs.msdn.com/maoni/archive/2005/05/06/415296.aspx">Using GC Efficiently, Part 4</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/01/great-links-on-using-garbage-collection-efficiently/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Resolvable</title>
		<link>http://davybrion.com/blog/2008/12/the-resolvable/</link>
		<comments>http://davybrion.com/blog/2008/12/the-resolvable/#comments</comments>
		<pubDate>Sun, 21 Dec 2008 14:48:26 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[Castle Windsor]]></category>
		<category><![CDATA[Memory Management]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=737</guid>
		<description><![CDATA[I wrote a post last week about a memory leak i had introduced in my code due to not properly releasing resolved components through the Windsor IoC container. I wanted to try to make sure that i&#8217;d never make that mistake again and this is the approach i came up with. If you&#8217;re using an [...]]]></description>
			<content:encoded><![CDATA[<p>I wrote a post last week about a memory leak i had introduced in my code due to <a href="http://davybrion.com/blog/2008/12/the-importance-of-releasing-your-components-through-windsor/">not properly releasing resolved components through the Windsor IoC container</a>.  I wanted to try to make sure that i&#8217;d never make that mistake again and this is the approach i came up with.</p>
<p>If you&#8217;re using an IOC container it&#8217;s important to not use it all over the place.  You basically use it in as few places as possible to resolve a component and you let the container sort out all of the dependencies.  So in the few places where you use the container directly, you need to resolve the component, and in case of transient components you also need to release them through the container.  Releasing it is very easy to forget, so i wanted something that would guarantee that the component would be properly released.  Enter the Resolvable class:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">Resolvable</span>&lt;T&gt; : <span style="color: #2b91af;">Disposable</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">readonly</span> T instance;</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> Resolvable() : <span style="color: blue;">this</span>(<span style="color: blue;">null</span>) {}</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> Resolvable(<span style="color: blue;">object</span> argumentsAsAnonymousType)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">if</span> (argumentsAsAnonymousType == <span style="color: blue;">null</span>)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; instance = <span style="color: #2b91af;">IoC</span>.Container.Resolve&lt;T&gt;();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">else</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; instance = <span style="color: #2b91af;">IoC</span>.Container.Resolve&lt;T&gt;(argumentsAsAnonymousType);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> T Instance</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">get</span> { <span style="color: blue;">return</span> instance; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">protected</span> <span style="color: blue;">override</span> <span style="color: blue;">void</span> DisposeManagedResources()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">IoC</span>.Container.Release(instance);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code> </p>
<p>The Resolvable class inherits from my <a href="http://davybrion.com/blog/2008/06/disposing-of-the-idisposable-implementation/">Disposable class</a>, so the Disposable pattern is correctly implemented.</p>
<p>From now on, instead of calling the container directly, i just instantiate a new Resolvable in a using block.  Let&#8217;s try it out.</p>
<p>I&#8217;m reusing my test component with a dependency from one of the previous posts:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">interface</span> <span style="color: #2b91af;">IDependency</span> : <span style="color: #2b91af;">IDisposable</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">bool</span> Disposed { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">MyDependency</span> : <span style="color: #2b91af;">IDependency</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">bool</span> Disposed { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">void</span> Dispose()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Disposed = <span style="color: blue;">true</span>;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">interface</span> <span style="color: #2b91af;">IController</span> : <span style="color: #2b91af;">IDisposable</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">bool</span> Disposed { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">IDependency</span> Dependency { <span style="color: blue;">get</span>; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">Controller</span> : <span style="color: #2b91af;">IController</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: #2b91af;">IDependency</span> Dependency { <span style="color: blue;">get</span>; <span style="color: blue;">private</span> <span style="color: blue;">set</span>; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> Controller(<span style="color: #2b91af;">IDependency</span> myDependency)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Dependency = myDependency;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">void</span> Dispose()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Dependency.Dispose();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Disposed = <span style="color: blue;">true</span>;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">bool</span> Disposed { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>Now, instead of resolving an IController directly through the container and having to dispose of it, i just do this:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; [<span style="color: #2b91af;">Test</span>]</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">void</span> ResolvableInstanceIsProperlyReleasedAfterDisposal()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">IoC</span>.Container.Register(<span style="color: #2b91af;">Component</span>.For&lt;<span style="color: #2b91af;">IController</span>&gt;().ImplementedBy&lt;<span style="color: #2b91af;">Controller</span>&gt;().LifeStyle.Transient);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">IoC</span>.Container.Register(<span style="color: #2b91af;">Component</span>.For&lt;<span style="color: #2b91af;">IDependency</span>&gt;().ImplementedBy&lt;<span style="color: #2b91af;">MyDependency</span>&gt;().LifeStyle.Transient);</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">IController</span> controller;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">IDependency</span> dependency;</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">using</span> (<span style="color: blue;">var</span> resolvable = <span style="color: blue;">new</span> <span style="color: #2b91af;">Resolvable</span>&lt;<span style="color: #2b91af;">IController</span>&gt;())</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; controller = resolvable.Instance;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; dependency = controller.Dependency;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">Assert</span>.IsTrue(controller.Disposed);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">Assert</span>.IsTrue(dependency.Disposed);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">Assert</span>.IsFalse(<span style="color: #2b91af;">IoC</span>.Container.Kernel.ReleasePolicy.HasTrack(controller));</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">Assert</span>.IsFalse(<span style="color: #2b91af;">IoC</span>.Container.Kernel.ReleasePolicy.HasTrack(dependency));</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>The container doesn&#8217;t hold the reference to the instance, and both the instance and its dependency is properly disposed. </p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2008/12/the-resolvable/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>The Component Burden</title>
		<link>http://davybrion.com/blog/2008/12/the-component-burden/</link>
		<comments>http://davybrion.com/blog/2008/12/the-component-burden/#comments</comments>
		<pubDate>Sun, 14 Dec 2008 12:37:23 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[Castle Windsor]]></category>
		<category><![CDATA[Memory Management]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=722</guid>
		<description><![CDATA[In my previous post i showed you how important it is to properly release the components you&#8217;ve resolved through the Windsor IoC container. At the end of that post, i showed an example where a disposable dependency of a component had to be disposed by the component. Basically something like this: &#160;&#160;&#160; public class Controller [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://davybrion.com/blog/2008/12/the-importance-of-releasing-your-components-through-windsor/">previous post</a> i showed you how important it is to properly release the components you&#8217;ve resolved through the Windsor IoC container.  At the end of that post, i showed an example where a disposable dependency of a component had to be disposed by the component.  Basically something like this:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">Controller</span> : <span style="color: #2b91af;">IController</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: #2b91af;">IDependency</span> Dependency { <span style="color: blue;">get</span>; <span style="color: blue;">private</span> <span style="color: blue;">set</span>; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> Controller(<span style="color: #2b91af;">IDependency</span> myDependency)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Dependency = myDependency;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">void</span> Dispose()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Dependency.Dispose();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>This prompted the following <a href="http://elegantcode.com/2008/12/13/the-importance-of-releasing-your-components-through-windsor/#comment-39632">comment</a> by Bryan Watts:</p>
<blockquote><p>
So Controller is responsible for disposing of something it did not explicitly create? That’s a little presumptuous isn’t it?</p>
<blockquote><p>
> if you own a reference to an IDisposable instance, you are responsible for properly disposing of that instance.
</p></blockquote>
<p>I agree (and I’ve read your other article). However, in this case, Controller clearly does not own its dependency.
</p></blockquote>
<p>And Bryan is right.  For a lot of languages, memory management rules can be summarized (somewhat simplified) like this:</p>
<ul>
<li>If you create an instance of a class, you are responsible for releasing/freeing/disposing it.</li>
<li>If a factory creates an instance of a class, the factory is not responsible for releasing/freeing/disposing it.  This burden falls upon the object which requested the object from the factory</li>
<li>If you receive an instance of an object, you should not release/free/dispose it, unless you received the instance from a factory</li>
</ul>
<p>So where does this leave us with the example code shown above?  Clearly, we did not create the instance of the disposable dependency, so in theory, we are not allowed to dispose it.  Then again, if we weren&#8217;t using Dependency Injection we would have probably instantiated the disposable dependency in our constructor (or when we first need it).  In that case, we would have been responsible for disposing the disposable dependency.  </p>
<p>You could argue that the IoC container is in some way a factory which creates and supplies the dependency to our class.  So according to the rules stated above, it would be allowed to dispose the dependency.   The downside to this is that this means that our class (the Controller) has knowledge of the lifecycle of the dependency.  We know that the dependency has been configured with a Transient lifecycle (which means the container creates a new instance whenever an instance of its class is needed) so we can safely dispose it.  The problem is that this knowledge is implicit.  It is nowhere visible in the code of the Controller class.  The only place where this lifecycle is configured explicitly, is in the configuration of the IoC container so it would be wrong for the Controller to assume anything about the lifecycle of its dependencies.  </p>
<p>After all, suppose someone makes a change to the code of the dependency which makes it possible to be used with a different lifecycle.  Suppose someone makes the change to the dependency and then configures the IoC container to always return a singleton instance of this dependency.  If nobody thinks about the fact that the Controller still assumes a Transient lifecycle of the dependency, the disposal of the dependency will not be removed from the Controller class.  Once a Controller instance is created, and then disposed, it will try to dispose the instance of its dependency, which will cause problems because that instance is supposed to be used by other objects as well!</p>
<p>So what do we do? Do we dispose of the dependency in the Controller class because we know it&#8217;s safe (until someone changes the dependency and/or its configuration with the container)?  Or do we simply not dispose it (since we&#8217;re not really allowed to do so without some kind of implicit knowledge of the &#8216;outside world&#8217;)?</p>
<p>Neither option sounds very appealing.  The first option <strong>could</strong> lead to problems depending on possible future changes outside of the Controller class.  The second option <strong>is already problematic</strong> because a disposable dependency is not being disposed of as fast as it should be.  The disposal would basically be postponed until the instance is collected by the garbage collector.</p>
<p>Another alternative is to have the container inject a factory which can create transient instances of the dependency, instead of having the container inject the transient instance directly.  This would fix all of the discussed problems: the controller would not need to dispose the injected dependency, and can safely dispose the instantiated disposable instances.  However, having to create factories simply to avoid this problem seems a bit cumbersome.  The implementation of the factory could lead to other discussions as well because of how the factory should create the actual instance <strong>and its dependencies</strong>, which is exactly the reason why we wanted to use an IoC container in the first place.  True, the factory could resolve the instance directly through the IoC container, but then you&#8217;re just moving the problem to a different class without actually fixing it properly.</p>
<p>This entire problem has been described as the <a href="http://hammett.castleproject.org/?p=252">Component Burden</a> by Hammet, the original creator of the Windsor IoC container.  Obviously, this is something that the container should solve for us instead of us having to worry about it.  Ideally, the container would keep track of all of the disposable dependencies it has created to satisfy the creation of requested components.  Then when the requested component would be released, the container could safely dispose of each transient disposable dependency it created to create the requested component.  Luckily, the Castle developers have implemented this behavior <a href="http://www.nabble.com/Component-burden-impl-committed-td19848831.html">recently</a>, so if you&#8217;re using a recent build of the Windsor IoC container,  this problem should no longer occur and you shouldn&#8217;t be forced to dispose of dependencies that were injected into your objects. </p>
<p>The reason why i&#8217;m not using it yet is because there were many attempts at implementing this, and most attempts had considerable downsides to them.  This one has been committed to the trunk, so it&#8217;s probably a good solution, but i&#8217;m not going to use this solution in production systems until it has had some more time to prove itself.  So for now, i&#8217;m sticking with my approach where i manually dispose the injected dependencies.  I know it&#8217;s not the best approach, but until the real solution in the container is somewhat more proven to work without downsides, manually disposing the dependencies seems to be the lesser of multiple evils.</p>
<p>Keep in mind that i&#8217;m only talking about the Windsor IoC container.  I have no experience with StructureMap, NInject or Unity, so i have no idea how these containers deal with this problems.  If anyone with knowledge about these container could shed some light on how they deal with this, i&#8217;d be very interested in reading it <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2008/12/the-component-burden/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>The Importance Of Releasing Your Components Through Windsor</title>
		<link>http://davybrion.com/blog/2008/12/the-importance-of-releasing-your-components-through-windsor/</link>
		<comments>http://davybrion.com/blog/2008/12/the-importance-of-releasing-your-components-through-windsor/#comments</comments>
		<pubDate>Sat, 13 Dec 2008 14:12:45 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[Castle Windsor]]></category>
		<category><![CDATA[Memory Management]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=718</guid>
		<description><![CDATA[We ran into a huge memory leak this week. A bit of memory profiling with JetBrains&#8217; dotTrace quickly showed that the Windsor IoC container was holding on to a lot of references. It turned out that i actually forgot to release the components i was requesting Windsor to construct for me. I use the container [...]]]></description>
			<content:encoded><![CDATA[<p>We ran into a huge memory leak this week. A bit of memory profiling with JetBrains&#8217; <a href="http://www.jetbrains.com/profiler/index.html">dotTrace</a> quickly showed that the Windsor IoC container was holding on to a lot of references. It turned out that i actually forgot to release the components i was requesting Windsor to construct for me. I use the container in my web-layer to compose every page&#8217;s Controller with its dependencies. And in my service layer, i use the container to compose every RequestHandler and its dependencies. So that&#8217;s two instances of the Container, in two separate AppDomains, and both are leaking a lot of memory due to my mistake.</p>
<p>My mistake was that after i was done with the components that i asked Windsor to resolve, i simply disposed them (which in turn would dispose their dependencies) and i figured that would be enough, since my components are registered as Transient. That means that each time you request a Transient component, you get a new instance. This led me to believe that Windsor wouldn&#8217;t need to hold a reference to the constructed components so i figured that simply disposing them would be enough, since they are IDisposables. Disposing them is a good thing obviously, but because the container was still holding references to the requested components, that&#8217;s still a lot of memory that is being wasted because even though you&#8217;ve disposed them, they aren&#8217;t eligible for Garbage Collection until they are no longer accessible. And because the container kept references to them, they remained accessible and were never collected. And there was my memory leak. Oops.</p>
<p>In order to prevent this problem in the future for myself and anyone else who reads this, let&#8217;s go over a few examples which should make it clear how you should make sure that your components are properly released so they are eligible for garbage collection.</p>
<p>Let&#8217;s start really simple. We have an IController interface and a simple Controller class which implements the IController interface:</p>
<p><code></code>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">interface</span> <span style="color: #2b91af">IController</span> : <span style="color: #2b91af">IDisposable</span></p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">bool</span> Disposed { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">Controller</span> : <span style="color: #2b91af">IController</span></p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">void</span> Dispose()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Disposed = <span style="color: blue">true</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">bool</span> Disposed { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
</p></div>
</p>
<p>In our tests, we&#8217;ll use the following method to create and configure the container:</p>
<p><code></code>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: #2b91af">WindsorContainer</span> CreateContainer()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> container = <span style="color: blue">new</span> <span style="color: #2b91af">WindsorContainer</span>();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; container.Register(<span style="color: #2b91af">Component</span>.For&lt;<span style="color: #2b91af">IController</span>&gt;().ImplementedBy&lt;<span style="color: #2b91af">Controller</span>&gt;().LifeStyle.Transient);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> container;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
</p></div>
</p>
<p>The IController interface is registered with the container, and the container will return a new Controller instance (because of the Transient lifestyle) whenever someone requests an IController instance.</p>
<p>The following test highlights the memory leak that i was experiencing:</p>
<p><code></code>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; [<span style="color: #2b91af">Test</span>]</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">void</span> ContainerKeepsReferenceToControllerIfWeOnlyDisposeOfIt()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> container = CreateContainer();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> controller = container.Resolve&lt;<span style="color: #2b91af">IController</span>&gt;();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">Assert</span>.That(container.Kernel.ReleasePolicy.HasTrack(controller));</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; controller.Dispose();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">Assert</span>.IsTrue(controller.Disposed);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: green">// the controller is disposed of, but the container is still keeping track</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: green">// of the instance</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">Assert</span>.That(container.Kernel.ReleasePolicy.HasTrack(controller));</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
</p></div>
</p>
<p>When you request a component from the Container, it keeps a reference to that instance in its Kernel&#8217;s ReleasePolicy object. If you merely dispose of your requested component, the ReleasePolicy still holds the reference to the component. This is what caused my memory leak.</p>
<p>So how do we avoid this problem? It&#8217;s pretty easy actually:</p>
<p><code></code>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; [<span style="color: #2b91af">Test</span>]</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">void</span> ContainerDoesNotKeepReferenceToControllerIfWeReleaseIt()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> container = CreateContainer();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> controller = container.Resolve&lt;<span style="color: #2b91af">IController</span>&gt;();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">Assert</span>.That(container.Kernel.ReleasePolicy.HasTrack(controller));</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: green">// instead of disposing the controller, we&#8217;ll Release it through the container</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; container.Release(controller);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">Assert</span>.IsTrue(controller.Disposed);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: green">// the controller is disposed of, and the container is no longer keeping</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: green">// track of the instance</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">Assert</span>.IsFalse(container.Kernel.ReleasePolicy.HasTrack(controller));</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
</p></div>
</p>
<p>Instead of just disposing our controller, we tell the container to release it. The container in turn knows that because IController inherits from IDisposable, it should dispose the Controller instance. It also removes the instance from its Kernel&#8217;s ReleasePolicy object and once your own reference to the Controller instance goes out of scope, it&#8217;s eligible to be collected by the Garbage Collector.</p>
<p>As you can see, it&#8217;s very easy to make sure your components are properly released and eligible for garbage collection. But what about possible dependencies of your components? Let&#8217;s take a look.</p>
<p>Suppose we define the following interface and implementation:</p>
<p><code></code>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">interface</span> <span style="color: #2b91af">IDependency</span> { }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">MyDependency</span> : <span style="color: #2b91af">IDependency</span> { }</p>
</p></div>
</p>
<p>The dependency doesn&#8217;t actually do anything, but bear with me <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>We modify the IController interface and Controller implementation like this:</p>
<p><code></code>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">interface</span> <span style="color: #2b91af">IController</span> : <span style="color: #2b91af">IDisposable</span></p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">bool</span> Disposed { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">IDependency</span> Dependency { <span style="color: blue">get</span>; }</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">Controller</span> : <span style="color: #2b91af">IController</span></p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: #2b91af">IDependency</span> Dependency { <span style="color: blue">get</span>; <span style="color: blue">private</span> <span style="color: blue">set</span>; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> Controller(<span style="color: #2b91af">IDependency</span> myDependency)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Dependency = myDependency;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">void</span> Dispose()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Disposed = <span style="color: blue">true</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">bool</span> Disposed { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
</p></div>
</p>
<p>And then we modify the configuration of the container like this:</p>
<p><code></code>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: #2b91af">WindsorContainer</span> CreateContainer()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> container = <span style="color: blue">new</span> <span style="color: #2b91af">WindsorContainer</span>();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; container.Register(<span style="color: #2b91af">Component</span>.For&lt;<span style="color: #2b91af">IController</span>&gt;().ImplementedBy&lt;<span style="color: #2b91af">Controller</span>&gt;().LifeStyle.Transient);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; container.Register(<span style="color: #2b91af">Component</span>.For&lt;<span style="color: #2b91af">IDependency</span>&gt;().ImplementedBy&lt;<span style="color: #2b91af">MyDependency</span>&gt;().LifeStyle.Transient);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> container;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
</p></div>
</p>
<p>Whenever we request an IController instance, the container will construct a Controller instance and will pass a MyDependency instance to the Controller&#8217;s instance constructor. The question now is: does the container also track the instances of a requested component&#8217;s dependencies? The answer is: no</p>
<p><code></code>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; [<span style="color: #2b91af">Test</span>]</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">void</span> ContainerDoesNotKeepReferenceToControllersDependencies()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> container = CreateContainer();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> controller = container.Resolve&lt;<span style="color: #2b91af">IController</span>&gt;();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">Assert</span>.That(container.Kernel.ReleasePolicy.HasTrack(controller));</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">Assert</span>.IsFalse(container.Kernel.ReleasePolicy.HasTrack(controller.Dependency));</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
</p></div>
</p>
<p>We request an IController instance, which is tracked by the container. The IController&#8217;s Dependency property contains an IDependency instance, which was also created by the container. But as the last line of the test shows: the container does not track instances of the requested IController&#8217;s dependencies.</p>
<p>So what does that mean? If the dependencies don&#8217;t require any cleanup, then this is great. We simply need to release the requested component, and the component and its dependencies will all be eligible for Garbage Collection. </p>
<p>(Note 27/01/10: the following part is no longer relevant as of Castle Windsor 2.1)</p>
<p>But what happens when the dependencies need to be disposed? Let&#8217;s take another look.</p>
<p>We modify the IDependency interface and MyDependency class so it looks like this:</p>
<p><code></code>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">interface</span> <span style="color: #2b91af">IDependency</span> : <span style="color: #2b91af">IDisposable</span></p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">bool</span> Disposed { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">MyDependency</span> : <span style="color: #2b91af">IDependency</span></p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">bool</span> Disposed { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">void</span> Dispose()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Disposed = <span style="color: blue">true</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
</p></div>
</p>
<p>Now let&#8217;s see what happens with the Controller&#8217;s dependencies when we release the Controller:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; [<span style="color: #2b91af">Test</span>]</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">void</span> ContainerDoesNotDisposeControllersDisposableDependencies()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> container = CreateContainer();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> controller = container.Resolve&lt;<span style="color: #2b91af">IController</span>&gt;();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> dependency = controller.Dependency;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">Assert</span>.That(container.Kernel.ReleasePolicy.HasTrack(controller));</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; container.Release(controller);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">Assert</span>.IsFalse(container.Kernel.ReleasePolicy.HasTrack(controller));&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">Assert</span>.IsFalse(container.Kernel.ReleasePolicy.HasTrack(dependency));</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">Assert</span>.IsTrue(controller.Disposed);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">Assert</span>.IsFalse(dependency.Disposed);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
</p></div>
<p>The container holds no references, but the Controller&#8217;s Dependency instance is not disposed! Notice however that the Controller has been disposed by the container. As i&#8217;ve mentioned <a href="http://davybrion.com/blog/2008/08/net-memory-management/">earlier</a>, if you own a reference to an IDisposable instance, you are responsible for properly disposing of that instance. So we modify the Controller&#8217;s Dispose method so that it looks like this:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">void</span> Dispose()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Dependency.Dispose();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Disposed = <span style="color: blue">true</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
</p></div>
<p>The previous test will now fail, because the Dependency will be properly disposed.</p>
<p>NOTE: i certainly don&#8217;t recommend to implement your Dispose methods like i just did. This is just a simplified example. The proper way to implement the Disposable Pattern is discussed <a href="http://davybrion.com/blog/2008/06/disposing-of-the-idisposable-implementation/">here</a>.</p>
<p>Anyways, i hope it&#8217;s clear now how you can make sure your IoC usage does not cause memory leaks, and that everything is properly disposed of.</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2008/12/the-importance-of-releasing-your-components-through-windsor/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Compiler Enforced Disposal?</title>
		<link>http://davybrion.com/blog/2008/11/compiler-enforced-disposal/</link>
		<comments>http://davybrion.com/blog/2008/11/compiler-enforced-disposal/#comments</comments>
		<pubDate>Sun, 16 Nov 2008 20:52:51 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[Memory Management]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=585</guid>
		<description><![CDATA[I stumbled upon a blog post by Kim Hamilton on When To Call Dispose. The most interesting part about the post is that this is from someone who works on the Base Class Libraries team. The following part is especially striking: A recent internal email thread unearthed extreme differences of opinion about when Dispose(void) should [...]]]></description>
			<content:encoded><![CDATA[<p>I stumbled upon a blog post by Kim Hamilton on <a href="http://blogs.msdn.com/kimhamil/archive/2008/11/05/when-to-call-dispose.aspx">When To Call Dispose</a>.  The most interesting part about the post is that this is from someone who works on the Base Class Libraries team.  The following part is especially striking:</p>
<blockquote><p>
A recent internal email thread unearthed extreme differences of opinion about when Dispose(void) should be called on an IDisposable. The rival suggestions were:</p>
<p>1. Always call Dispose</p>
<p>2. Avoid calling Dispose; rely on cleanup at finalization</p>
<p>This led to a long discussion and a realization that &#8212; while it seems like we’ve said everything there is to say about Dispose &#8212; it’s time for some more Dispose guidance.
</p></blockquote>
<p>I don&#8217;t know about you guys, but the thought of Base Class Library developers not being sure on when Dispose should be called is something that makes me quite uncomfortable. If anyone should know, it&#8217;s these guys, right?</p>
<p>Another interesting quote from the post:</p>
<blockquote><p>
Whatever distinction we eventually use, API docs should explicitly call out IDisposables that must be Disposed.
</p></blockquote>
<p>Great&#8230; now we are supposed to rely on the MSDN docs to find out which IDisposables need to be disposed and which ones don&#8217;t. </p>
<p>I kinda like the IDisposable pattern, but it&#8217;s truly a shame that there are so many types that implement the IDisposable interface without really needing to implement it.  I&#8217;ve always considered the IDisposable interface to be a contract which states &#8220;if you use me, you must dispose me&#8221;. For certain types, this is true.  Unfortunately, for other types that implement the interface it&#8217;s not true even though the <a href="http://msdn.microsoft.com/en-us/library/system.idisposable.aspx">IDisposable documentation</a> is pretty clear about this:</p>
<blockquote><p>When calling a class that implements the IDisposable interface, use the try/finally pattern to make sure that unmanaged resources are disposed of even if an exception interrupts your application.</p></blockquote>
<p>In a perfect .NET world, there would be no types implementing IDisposable without actually requiring disposal (IMHO).  Again, i think the interface is a contract that must be followed by everyone who makes use of it.  Then again, it does feel pretty pointless to dispose types of which you know that it really doesn&#8217;t make a difference.</p>
<p>The introduction of explicit <a href="http://blogs.msdn.com/bclteam/archive/2008/11/11/introduction-to-code-contracts-melitta-andersen.aspx">Code Contracts in .NET 4.0</a>, got me thinking about trying to make disposal of types that really require it enforced by the compiler.  What i have in mind is not possible with the Code Contracts in .NET 4.0, but it&#8217;s something that i think would be a good addition to the .NET Framework.</p>
<p>Suppose we could do the following:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; [<span style="color: #2b91af;">RequiresDisposal</span>]</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">MyDisposableType</span> : <span style="color: #2b91af;">IDisposable</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">void</span> DoSomething()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// does something really cool and/or important</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">void</span> Dispose()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// this would contain an important disposable implementation</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>Basically just a type which implements IDisposable, and there&#8217;s an attribute that specifies that the disposal of this type is really required.  The following code should then fail to compile:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">void</span> SomeMethod()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">new</span> <span style="color: #2b91af;">MyDisposableType</span>().DoSomething();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>Whereas this code would compile without errors:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">void</span> SomeMethod()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">using</span> (<span style="color: blue;">var</span> disposableType = <span style="color: blue;">new</span> <span style="color: #2b91af;">MyDisposableType</span>())</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; disposableType.DoSomething();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code> </p>
<p>It&#8217;s just a thought and obviously, this isn&#8217;t possible right now.  But i think it would be great if it were possible.  We could do all sorts of things with this approach&#8230; for instance, if an object owns a reference to an IDisposable type which has the [RequiresDisposal] attribute, the compiler could enforce that the object owning the reference must implement IDisposable and have the [RequiresDisposal] attribute as well.  I think we&#8217;d end up with a system were types that really require disposal can&#8217;t be used without properly disposing them.</p>
<p>Thoughts?</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2008/11/compiler-enforced-disposal/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Do Not .Dispose In The PreRender Event</title>
		<link>http://davybrion.com/blog/2008/10/do-not-dispose-in-the-prerender-event/</link>
		<comments>http://davybrion.com/blog/2008/10/do-not-dispose-in-the-prerender-event/#comments</comments>
		<pubDate>Wed, 01 Oct 2008 19:43:31 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Memory Management]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=472</guid>
		<description><![CDATA[We had this weird issue with a project at work&#8230; sometimes, the web application would just completely hang for a couple of minutes. A coworker started looking at the problem, and he quickly found out that in some cases, calls to the WCF service would just completely block. Even when debugging the web application and [...]]]></description>
			<content:encoded><![CDATA[<p>We had this weird issue with a project at work&#8230; sometimes, the web application would just completely hang for a couple of minutes. A coworker started looking at the problem, and he quickly found out that in some cases, calls to the WCF service would just completely block.  Even when debugging the web application and the WCF service on our development machines, so it wasn&#8217;t an issue of throughput or concurrency or anything like that on the server.</p>
<p>We were clueless as to why the calls were actually blocking. We had a few scenarios that would <strong>usually</strong> (but not always) trigger the bug, but it also occurred in other situations, seemingly at random.  So my coworker spent many hours trying to find out why it was happening. After a lot of debugging on his part, he found out that sometimes our WCF proxies weren&#8217;t being disposed, which left Channels to the service open which caused new proxies to block whenever the number of allowed concurrent channels was reached. My first reaction was &#8220;huh, how could that be? i&#8217;m disposing of them in the page&#8217;s PreRender event&#8230;&#8221;.</p>
<p>First of all, i&#8217;m far from an ASP.NET guru, so those of you who do know a lot about it probably already understand the problem. I figured that the PreRender event would always occur, and that it would be the best place to dispose the WCF proxy.  That turned out to be a two-for-one brain fart on my part.  First of all, the PreRender event is obviously not fired when you do a Server.Redirect or Server.Transfer, so whenever we navigated to another page, we did not dispose our WCF proxy.  Secondly, Page inherits IDisposable, which i completely missed apparently.  So, had i simply overridden the Dispose method and dispose the proxy in there before calling base.Dispose() and then we would&#8217;ve never had this problem to begin with.</p>
<p>Lesson of the day: no matter how careful you try to be, you can still fuck up pretty bad sometimes <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Update: i actually used the PreRenderComplete event instead of the PreRender event&#8230; still, a bad place to dispose of disposable objects <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2008/10/do-not-dispose-in-the-prerender-event/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Why you should always unscubscribe event handlers</title>
		<link>http://davybrion.com/blog/2008/08/why-you-should-always-unscubscribe-event-handlers/</link>
		<comments>http://davybrion.com/blog/2008/08/why-you-should-always-unscubscribe-event-handlers/#comments</comments>
		<pubDate>Sun, 17 Aug 2008 18:55:20 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[Memory Management]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=325</guid>
		<description><![CDATA[Events in .NET are very useful. But if you&#8217;re not careful, they might prevent objects from being removed from memory by the Garbage Collector (GC). Let&#8217;s call an object that publishes an event a Publisher and an object that subscribes to an event a Subscriber. If a Subscriber subscribes to a Publisher&#8217;s event, the Publisher [...]]]></description>
			<content:encoded><![CDATA[<p>Events in .NET are very useful. But if you&#8217;re not careful, they might prevent objects from being removed from memory by the Garbage Collector (GC).  Let&#8217;s call an object that publishes an event a Publisher and an object that subscribes to an event a Subscriber. If a Subscriber subscribes to a Publisher&#8217;s event, the Publisher will indirectly hold a reference to the Subscriber (because of how events in .NET are implemented).  If the Publisher is an object that will stay around for a long time, this could prevent the Subscriber from being removed from memory when it&#8217;s no longer used.</p>
<p>Suppose we have the following Publisher class:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">Publisher</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">event</span> <span style="color: #2b91af;">EventHandler</span> MyEvent;</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">void</span> FireEvent()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">if</span> (MyEvent != <span style="color: blue;">null</span>)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; MyEvent(<span style="color: blue;">this</span>, <span style="color: #2b91af;">EventArgs</span>.Empty);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>And then we have a BadSubscriber class:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">BadSubscriber</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> BadSubscriber(<span style="color: #2b91af;">Publisher</span> publisher)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; publisher.MyEvent += publisher_MyEvent;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">void</span> publisher_MyEvent(<span style="color: blue;">object</span> sender, <span style="color: #2b91af;">EventArgs</span> e)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">Console</span>.WriteLine(<span style="color: #a31515;">"the publisher notified the bad subscriber of an event"</span>);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>Notice how the BadSubscriber subscribes to the Publisher&#8217;s event, but never unsubscribes from it.</p>
<p>Then we have the GoodSubscriber:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">GoodSubscriber</span> : <span style="color: #2b91af;">IDisposable</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">readonly</span> <span style="color: #2b91af;">Publisher</span> publisher;</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> GoodSubscriber(<span style="color: #2b91af;">Publisher</span> publisher)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">this</span>.publisher = publisher;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; publisher.MyEvent += publisher_MyEvent;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">void</span> publisher_MyEvent(<span style="color: blue;">object</span> sender, <span style="color: #2b91af;">EventArgs</span> e)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">Console</span>.WriteLine(<span style="color: #a31515;">"the publisher notified the good subscriber of an event"</span>);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">void</span> Dispose()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; publisher.MyEvent -= publisher_MyEvent;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>The GoodSubscriber is very similar to the BadSubscriber, but it unsubscribes from the Publisher&#8217;s event when it is disposed.  Note that the implementation of the IDisposable interface is hardly ideal, but for the purpose of this demo it&#8217;s sufficient.</p>
<p>The following code illustrates the problem:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">static</span> <span style="color: blue;">void</span> Main(<span style="color: blue;">string</span>[] args)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> publisher = <span style="color: blue;">new</span> <span style="color: #2b91af;">Publisher</span>();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> badSubscriber = <span style="color: blue;">new</span> <span style="color: #2b91af;">BadSubscriber</span>(publisher);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> goodSubscriber = <span style="color: blue;">new</span> <span style="color: #2b91af;">GoodSubscriber</span>(publisher);</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> badSubscriberRef = <span style="color: blue;">new</span> <span style="color: #2b91af;">WeakReference</span>(badSubscriber);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> goodSubscriberRef = <span style="color: blue;">new</span> <span style="color: #2b91af;">WeakReference</span>(goodSubscriber);</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; publisher.FireEvent();</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; badSubscriber = <span style="color: blue;">null</span>;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; goodSubscriber.Dispose();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; goodSubscriber = <span style="color: blue;">null</span>;</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">GC</span>.Collect();</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">Console</span>.WriteLine(goodSubscriberRef.IsAlive ? <span style="color: #a31515;">"good publisher is alive"</span> : <span style="color: #a31515;">"good publisher is gone"</span>);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">Console</span>.WriteLine(badSubscriberRef.IsAlive ? <span style="color: #a31515;">"bad publisher is alive"</span> : <span style="color: #a31515;">"bad publisher is gone"</span>);</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; publisher.FireEvent();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>The output of that code is the following:</p>
<p>the publisher notified the bad subscriber of an event<br />
the publisher notified the good subscriber of an event<br />
good publisher is gone<br />
bad publisher is alive<br />
the publisher notified the bad subscriber of an event</p>
<p>Notice how the GoodSubscriber is removed from memory by the GC and how the BadSubscriber is still in memory even though we no longer have a reference to it and the GC has performed a collection.</p>
<p>So keep in mind that every event handler you subscribe to an event should be properly unsubscribed from the event when your instance is no longer needed. Not doing so might lead to instances not being removed if the event&#8217;s publisher has a longer lifetime than your object will have.  I&#8217;d actually suggest you&#8217;d always properly unsubscribe from any event you subscribe to.  Even if you know that the Publisher won&#8217;t have a longer lifetime than your instance will have, who&#8217;s to say some future change in the code won&#8217;t extend the lifetime of the Publisher over that of the Subscriber? When that happens, you might end up with a bunch of instances that will remain in memory as long as the Publisher remains in memory.</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2008/08/why-you-should-always-unscubscribe-event-handlers/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>.NET Memory Management</title>
		<link>http://davybrion.com/blog/2008/08/net-memory-management/</link>
		<comments>http://davybrion.com/blog/2008/08/net-memory-management/#comments</comments>
		<pubDate>Sat, 16 Aug 2008 18:44:32 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[Memory Management]]></category>
		<category><![CDATA[Patterns]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=311</guid>
		<description><![CDATA[Introduction Garbage Collection sure is great, isn&#8217;t it? We don&#8217;t have to keep track of all the memory we&#8217;ve allocated and we don&#8217;t need to release that memory when it&#8217;s no longer needed. Because that is after all what the Garbage Collector does for us, without us having to worry about it. This is actually [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Garbage Collection sure is great, isn&#8217;t it? We don&#8217;t have to keep track of all the memory we&#8217;ve allocated and we don&#8217;t need to release that memory when it&#8217;s no longer needed. Because that is after all what the Garbage Collector does for us, without us having to worry about it.  This is actually a widespread misconception among many .NET developers.  It&#8217;s true that Garbage Collection makes memory management a lot easier, but we simply can&#8217;t rely on it all the time. There are most certainly some things you must always keep in mind when it comes to memory management in .NET.</p>
<h2>Different Kinds Of Resources, Different Consequences</h2>
<p>In most pieces of code, you use variables. A lot of these variables are references to objects. When your variables go out of scope, they no longer exist.  When those variables are references to objects, only your reference is gone and the actual object that was referred to is still in memory somewhere. The Garbage Collector (GC) makes sure that orphaned objects (objects that no longer have a usable reference to them) are removed from memory. This is an automatic process within the .NET runtime.  Essentially, the GC periodically performs some checks on objects and if it comes to the conclusion that certain objects are no longer needed, it will remove them from memory.  This is a gross oversimplification of how it really works, but that is what it comes down to and that is also how most people think about the GC.</p>
<p>The GC in .NET is very smart and will almost always do a better job of memory management than you will. But there is one huge downside to it: the GC runs periodically and you have no deterministic way of knowing when it will run.  Sure, you can instruct the GC to perform a collection but in most cases that will actually have a negative impact on the memory management of your application.  I won&#8217;t go into the details here, but i will provide a follow-up post on this later on. For now, keep in mind that forcing a garbage collection to occur is really something you should avoid.</p>
<p>So is it really a problem that you don&#8217;t know for certain when the GC will run? It depends on which kind of objects that need to be removed from memory.  There are basically 2 kinds: managed and unmanaged resources. Managed resources are typical .NET types. Unmanaged resources (also referred to as Native Resources) are things that fall outside of the scope of the .NET managed environment.  These are usually things that are available within the Operating System, or that are available through lower-level development API&#8217;s (such as the Win32 API for instance).  Unmanaged resources can&#8217;t be cleaned up automatically by the .NET runtime, so if you use them directly, you are responsible for cleaning up after you&#8217;ve used them. Luckily, a lot of managed types are available that take care of the dirty details for you.  For instance, if you need to use a file in .NET, you&#8217;ll typically use a FileStream instance or something else that easily makes the content of the file available to you, or that easily allows you to write content to a file.  The FileStream is a managed type, but it uses unmanaged resources to implement the functionality it offers.  </p>
<p>Now think about this: you are using a managed type, so you shouldn&#8217;t need to perform any cleanup, right?  However, if that managed type uses unmanaged resources then they still need to be cleaned up. And those unmanaged resources should be cleaned up as soon as possible because they can be quite expensive.  These types usually offer a way to clean up the unmanaged resources they use in a deterministic manner.  They usually implement the IDisposable interface, which exposes a Dispose method.  When you call the Dispose method, the unmanaged resources are cleaned up right then and there and then there&#8217;s no need to wait for the garbage collector, which again, could be quite expensive when you (either directly or indirectly) have a bunch of unmanaged resources in memory that are waiting to be cleaned up.  </p>
<h2>Disposable Managed Resources</h2>
<p>I call types that implement the IDisposable interface Disposable Managed Resources. They are indeed managed types and thus they are guaranteed to be cleaned up when the GC comes around and notices that instances of these types are no longer needed.  However, if you merely trust on the GC to clean up instances of these types you are taking quite a risk. Any expensive resource it may hold might be cleaned up a lot later than it could have been.  Which can be very inefficient, and thus, quite costly.  </p>
<p>If a type implements the IDisposable interface, it usually has a good reason for doing so (there are of course exceptions to the rule). It is essentially a way of telling consumers of the type that it offers a deterministic way of cleaning up the resources it consumes and i believe you should take advantage of that.  If you don&#8217;t, you may end up with inefficient memory management, and that&#8217;s when people start complaining that Garbage Collection is &#8216;evil&#8217; or that it &#8216;sucks&#8217;. In most cases, people who feel that way simply don&#8217;t know how to use it properly.  The IDisposable interface and the Dispose Pattern (which we&#8217;ll get to in a minute) allow you to avoid most of the issues that are generally attributed to the Garbage Collection in general.</p>
<p>So how do we deal with this? First of all, if a type uses unmanaged resources, it should implement the IDisposable interface using the Dispose Pattern. Secondly, if any of your types use other types that implement IDisposable, it is your responsibility to make sure these types are properly disposed of.  You either dispose them when you no longer need them, or you must implement IDisposable and the Dispose Pattern yourself to make sure the Disposable Managed Resources you depend on are indeed properly disposed of.  If you need to implement IDisposable, your type effectively becomes a Disposable Managed Resource itself.  A lot of people think that this isn&#8217;t necessary, but by not doing so they are breaking the contract that the IDisposable interface implies. If a type implements IDisposable then either that type or any other type it may use probably uses unmanaged resources somewhere and you want to see these get cleaned up as soon as possible.  Because of that, i believe it&#8217;s best to implement IDisposable yourself if you&#8217;re holding any reference to a type that also implements it.</p>
<h2>The Dispose Pattern</h2>
<p>Implementing the IDisposable interface can be as easy as merely providing a public Dispose method where you perform your cleanup.  That&#8217;s really not a good way of doing it though, as it could lead to a bunch of other problems which might actually make the situation worse.  The best way to implement the IDisposable interface is to implement the Dispose Pattern, which looks like this:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">MyDisposableClass</span> : <span style="color: #2b91af;">IDisposable</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">bool</span> disposed = <span style="color: blue;">false</span>;</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">void</span> Dispose()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Dispose(<span style="color: blue;">true</span>);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// prevent this object from being placed in the finalization queue if some</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// derived class provides a finalizer</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">GC</span>.SuppressFinalize(<span style="color: blue;">this</span>);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <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;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">if</span> (!disposed)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">if</span> (disposing)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// dispose all Disposable Managed Resources here</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// dispose all Unmanaged Resources here</span></p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// set disposed to true to prevent the code above from being</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// executed a second time</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; disposed = <span style="color: blue;">true</span>;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>If you don&#8217;t need a finalizer it&#8217;s best not to provide one (we&#8217;ll discuss finalizers later on).  If you do need one, you would implement it like this:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> ~MyDisposableClass()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Dispose(<span style="color: blue;">false</span>);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>So what&#8217;s so good about the Dispose pattern? Well, we make a clear distinction between what should happen when the object is disposed through the Dispose method, or when it&#8217;s being cleaned up by the finalizer. When the clean up occurs through a call to Dispose, it calls the protected virtual Dispose method with the disposing parameter set to true. When this parameter is true, you should call the Dispose method of each Disposable Managed Resource you&#8217;re holding a reference to. Outside of the if-statement, you should clean up each unmanaged resource you may be holding.</p>
<p>If your class (or a derived class) implements a finalizer method, it should call the Dispose method with the disposing parameter set to false.  The reason for this is that the order in which objects are finalized is not specified. If you&#8217;re not careful, you could accidentally call the Dispose method of a Disposable Managed Resource which may have already been finalized as well.  This would cause an exception and a finalizer method should never ever throw an exception because that could keep other objects from being finalized.</p>
<p>If you can, try to put this pattern into a reusable base class and make your Disposable Managed Resource holding types inherit from this.  An example of this approach can be found <a href="http://davybrion.com/blog/2008/06/disposing-of-the-idisposable-implementation/">here</a>.</p>
<h2>Using Disposable Managed Resources</h2>
<p>In a lot of cases, you will use a Disposable Managed Resource within the scope of one method. In that case, you certainly don&#8217;t need to implement IDisposable. There are two things to keep in mind though. If you receive the Disposable Managed Resource as a method parameter, you are not responsible for disposing it! Somebody else created it, let them take care of the disposal. Things will most likely go wrong if you dispose objects that have been giving to you by somebody else. So in this case, you would just use the object and not worry about it any further:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">void</span> DoSomethingInteresting(<span style="color: #2b91af;">MyDisposableClass</span> disposableResource)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// ... some code could go here</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; disposableResource.DoWhateverItIsThatMakesYouSoSpecial();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// ... some code could go here</span></p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// we reach the end of the method and we haven't Disposed the</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// Disposable Managed Resource because it wasn't our responsibility</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>However, if you create the object yourself, then you are responsible for getting rid of it properly. In that case, use a using block to make sure the object is disposed of even in case of unhandled exceptions:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">void</span> DoSomethingInteresting()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// ... some code could go here</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">using</span> (<span style="color: blue;">var</span> myDisposableResource = <span style="color: blue;">new</span> <span style="color: #2b91af;">MyDisposableClass</span>())</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; myDisposableResource.DoWhateverItIsThatMakesYouSoSpecial();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// ... some code could go here</span></p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// we reach the end of the method and we properly Disposed the</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// Disposable Managed Resource because it was our responsibility</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>In case you don&#8217;t know, the using-block guarantees that the Dispose method will be called when we leave the scope of the block.  It can get pretty tricky sometimes if you&#8217;re passing the Disposable Managed Resources to other objects that will hold a reference to them which will remain in use after you&#8217;ve left the using block. In this scenario, it&#8217;s possible that the object you&#8217;ve passed the Disposable Managed Resource to will try to invoke methods on the disposed instance. Also a situation you most certainly want to avoid because it will either cause unexpected behavior or even unhandled exceptions. The unhandled exceptions are easy to figure out, but the unexpected behavior might be difficult to debug.  The key in this scenario, is to figure out a way to not call Dispose on the resource until the other object is done with it.  Sometimes it might be enough to put your using block on a slightly higher level, other times you&#8217;ll have to keep a reference to the resource yourself, which effectively means you&#8217;ve now become an owner of the Disposable Managed Resource.</p>
<h2>Owning Disposable Managed Resources</h2>
<p>If you need to hold a reference to a Disposable Managed Resource, you are either the owner of the object or at least someone who owns a stake in the lifetime of the object.  If you are the owner, and you do not pass the Disposable Managed Resource to any other object then the solution is easy: implement IDisposable.  If you do pass the Disposable Managed Resource to other objects, then it can get tricky. Will they only use it to perform some action or will they hold a reference to it?  If they hold a reference to it, it means that they too have a stake in the lifetime of the resource.  Depending on the implementation of the other types, they may or may not call the Dispose method of the instance you created. Which could cause unexpected behavior or exceptions in your code. Make sure you are prepared for that if you&#8217;re passing these objects around. But you should definitely dispose of them in your own Dispose method.</p>
<p>If you didn&#8217;t create the Disposable Managed Resource, but you do need to hold a reference to it, then you&#8217;ve got some questions to answer. Does the type which provided you with the instance expect you to be solely responsible for the lifetime of the object? In case of factory classes or factory methods, the answer is usually &#8216;yes&#8217;.  If you&#8217;ve been given the instance by something that will probably make use of that same instance, i think it&#8217;s better not to dispose it.  Some people will probably disagree, but i don&#8217;t think it&#8217;s my responsibility to dispose objects that i didn&#8217;t create, unless the instance was given to me by a factory class or a factory method.  I would expect that the real owner of the resource would dispose of it. Still, it&#8217;s a difficult call to make.</p>
<h2>Finalizers</h2>
<p>Finally, i&#8217;d like to add a few words about Finalizers in .NET.  A finalizer is similar to a destructor in C++, in that it is the code that is run when your object is being removed from memory. The big difference is that you never know for sure when it will be run, which is why the IDisposable interface and the Dispose pattern was created. There are a lot of misconceptions going around about finalizers, so keep the following comments in mind. </p>
<p>First of all, finalizers only make sense when you have direct references to unmanaged resources. If you have unmanaged resources, implement IDisposable and provide a finalizer that calls the Dispose overload with the disposing parameter set to false. This should really be the only code inside your finalizer method. </p>
<p>Finalizers also come with a performance penalty. When finalizable objects are created, pointers to these objects are added to the finalization queue of the GC.  These finalizable objects are collected less frequently because the GC performs finalizations through its finalization queue. This finalization process is not executed as frequently as regular garbage collections because it&#8217;s quite costly. So not only are finalizable objects cleaned up less frequently, it takes more processing power to do so.  So if you have a lot of finalizable instances, your code&#8217;s performance can easily be impacted because of this.  </p>
<h2>Conclusion</h2>
<p>I hope i made it clear that there is a lot more to automatic memory management in .NET than simply relying on the GC to take care of all of the details for you. There is a lot more stuff that i didn&#8217;t cover in this post (it&#8217;s long enough already) but most .NET developers will probably get by pretty well with the advice given in this post.  It&#8217;s not an easy subject to explain so i hope everything was clear <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2008/08/net-memory-management/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Disposing of the IDisposable implementation</title>
		<link>http://davybrion.com/blog/2008/06/disposing-of-the-idisposable-implementation/</link>
		<comments>http://davybrion.com/blog/2008/06/disposing-of-the-idisposable-implementation/#comments</comments>
		<pubDate>Tue, 17 Jun 2008 13:01:36 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[Memory Management]]></category>
		<category><![CDATA[Patterns]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=147</guid>
		<description><![CDATA[Everytime i need to implement the IDisposable interface i have to lookup the recommended way of doing so. That in itself is a bad sign, so i figured i might as well get rid of this by putting the implementation in a reusable base class, based on the officially recommended way: &#160;&#160;&#160; public abstract class [...]]]></description>
			<content:encoded><![CDATA[<p>Everytime i need to implement the IDisposable interface i have to lookup the recommended way of doing so. That in itself is a bad sign, so i figured i might as well get rid of this by putting the implementation in a reusable base class, based on <a href="http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx">the officially recommended way</a>:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">abstract</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">Disposable</span> : <span style="color: #2b91af;">IDisposable</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">bool</span> disposed;</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">void</span> Dispose()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Dispose(<span style="color: blue;">true</span>);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">GC</span>.SuppressFinalize(<span style="color: blue;">this</span>);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">protected</span> <span style="color: blue;">void</span> Dispose(<span style="color: blue;">bool</span> disposing)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">if</span> (!disposed)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">if</span> (disposing)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; DisposeManagedResources();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; DisposeUnmanagedResources();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; disposed = <span style="color: blue;">true</span>;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">protected</span> <span style="color: blue;">void</span> ThrowExceptionIfDisposed()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">if</span> (disposed)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">throw</span> <span style="color: blue;">new</span> <span style="color: #2b91af;">ObjectDisposedException</span>(GetType().FullName);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">protected</span> <span style="color: blue;">abstract</span> <span style="color: blue;">void</span> DisposeManagedResources();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">protected</span> <span style="color: blue;">virtual</span> <span style="color: blue;">void</span> DisposeUnmanagedResources() {}</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>So now i can simply inherit from Disposable, and i just need to implement the two abstract methods.  Here&#8217;s a made up example to illustrate this:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">MyExpensiveResource</span> : <span style="color: #2b91af;">Disposable</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: #2b91af;">FileStream</span> fileStream;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: #2b91af;">MemoryStream</span> memoryStream;</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> MyExpensiveResource(<span style="color: blue;">string</span> path)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; fileStream = <span style="color: blue;">new</span> <span style="color: #2b91af;">FileStream</span>(path, <span style="color: #2b91af;">FileMode</span>.Open);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; memoryStream = <span style="color: blue;">new</span> <span style="color: #2b91af;">MemoryStream</span>();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">void</span> DoSomething()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; ThrowExceptionIfDisposed();</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// ... something</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">protected</span> <span style="color: blue;">override</span> <span style="color: blue;">void</span> DisposeManagedResources()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">if</span> (fileStream != <span style="color: blue;">null</span>) fileStream.Dispose();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">if</span> (memoryStream != <span style="color: blue;">null</span>) memoryStream.Dispose();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>Obviously, you can&#8217;t use the Disposable base class if you&#8217;re already inheriting from another base class so in that case you&#8217;d still have to implement the IDisposable interface.</p>
<p><strong>Update</strong>: <a href="http://blog.quantumbitdesigns.com/2008/07/22/a-thread-safe-idisposable-base-class/">Here</a>&#8216;s a thread-safe version of this idea.</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2008/06/disposing-of-the-idisposable-implementation/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
	</channel>
</rss>
