<?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>design patterns Archives - CodeJourney.net</title>
	<atom:link href="https://www.codejourney.net/tag/design-patterns/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.codejourney.net/tag/design-patterns/</link>
	<description>Building real-world software with AI 🤖</description>
	<lastBuildDate>Thu, 24 Aug 2023 15:49:04 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0</generator>

<image>
	<url>https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/cropped-512px-na-512px-JPEG-BEZ-NAPISU-1.jpg?fit=32%2C32&#038;ssl=1</url>
	<title>design patterns Archives - CodeJourney.net</title>
	<link>https://www.codejourney.net/tag/design-patterns/</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">123174533</site>	<item>
		<title>How (And Why?) To Wrap External Libraries?</title>
		<link>https://www.codejourney.net/how-and-why-to-wrap-external-libraries/</link>
					<comments>https://www.codejourney.net/how-and-why-to-wrap-external-libraries/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Mon, 20 Feb 2023 09:00:00 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[npm]]></category>
		<category><![CDATA[road-to-dotnet-full-stack]]></category>
		<category><![CDATA[typescript]]></category>
		<guid isPermaLink="false">https://www.codejourney.net/?p=4346</guid>

					<description><![CDATA[<p>If you use external libraries in your application, wrapping them may be very helpful. How to wrap external libraries and why it&#8217;s worth doing that? Today we&#8217;re going to dive into that, based on a TypeScript web app example 😉 Why? You probably know what a&#160;wrapper is. As its name suggests, it&#8217;s a practice of&#8230;</p>
<p>The post <a href="https://www.codejourney.net/how-and-why-to-wrap-external-libraries/">How (And Why?) To Wrap External Libraries?</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">If you use external libraries in your application, wrapping them may be very helpful. How to wrap external libraries and why it&#8217;s worth doing that? Today we&#8217;re going to dive into that, based on a TypeScript web app example <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<span id="more-4346"></span>



<h2 class="wp-block-heading">Why?</h2>



<p class="wp-block-paragraph">You probably know what a&nbsp;<em>wrapper</em> is. As its name suggests, it&#8217;s a practice of putting another layer on a piece of something. In our case, <em>wrapping</em>&nbsp;a piece of code in another piece of code <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p class="wp-block-paragraph">But why would you do that? To make your life easier! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4aa.png" alt="💪" class="wp-smiley" style="height: 1em; max-height: 1em;" /><br>Wrapping external libraries lets you abstract your code from their implementation details. In effect, it makes your life a lot easier when you want to keep the behavior, but change the library providing it. This approach also lets you use only those features from a given external dependency that you actually need.<br>Let&#8217;s see that with an example.</p>



<h2 class="wp-block-heading">Wrapping HTTP client</h2>



<p class="wp-block-paragraph">A very good example is HTTP client&nbsp;wrapper. HTTP calls are used in almost every web application. In order to perform them, we need to choose an HTTP client. We can either use <code><a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch">fetch</a></code>, or something more sophisticated like&nbsp;<code><a href="https://axios-http.com/docs/intro">axios</a></code>.</p>



<p class="wp-block-paragraph">However, with time, we may decide to replace it with something else. There might be many reasons for that &#8211; either the library stops to be maintained or something new and better is out there. It would be a shame if we&#8217;d now need to change the code in those thousands of places where the current library is being used. This would take a lot of time and might be error-prone. We can definitely prepare better for such cases <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h3 class="wp-block-heading">Create HttpClient wrapper for axios</h3>



<p class="wp-block-paragraph">Let&#8217;s say that, for now, we will go with <code>axios</code>. Instead of <a href="https://axios-http.com/docs/example">calling it directly from our code</a>:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-line="2,10-11" data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">import { useEffect, useState } from &quot;react&quot;;<br/>import axios from &quot;axios&quot;;<br/>import { Product } from &quot;../types/product&quot;;<br/>import { DummyJsonProductsResult } from &quot;../types/dummyJsonProductsResult&quot;;<br/><br/>export const ProductsList = () =&gt; {<br/>  const [products, setProducts] = useState&lt;Product[] | null&gt;(null);<br/><br/>  useEffect(() =&gt; {<br/>    axios<br/>      .get&lt;DummyJsonProductsResult&gt;(&quot;https://dummyjson.com/products&quot;)<br/>      .then((result) =&gt; {<br/>        setProducts(result.data.products);<br/>      });<br/>  }, []);<br/> <br/> // ...<br/>};</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">ProductsList.tsx &#8211; calling axios directly from component&#039;s code</span> </div> </div></div>



<p class="wp-block-paragraph">I will create an <em>HttpClient</em> wrapper for it and use it instead.</p>



<p class="wp-block-paragraph">First, I create <code>httpClient.ts</code> file in <code>wrappers</code> folder. I like to have such a catalog in my React projects and keep all the wrappers there.</p>



<p class="wp-block-paragraph">I start writing all wrappers with an interface. In that case, I treat the interface as a <em>contract</em>. It should say what I need this small wrapper to do, without worrying about implementation details.</p>



<p class="wp-block-paragraph"><code>IHttpClient</code> interface initially looks as follows:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">interface IHttpClient {<br/>  get&lt;TResponse&gt;(url: string): Promise&lt;TResponse&gt;;<br/>}</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">httpClient.ts &#8211; IHttpClient interface (get only)</span> </div> </div></div>



<p class="wp-block-paragraph">That&#8217;s what we have so far. We just need to retrieve the data with <code>GET</code> method.</p>



<p class="wp-block-paragraph">Next step is to create the actual implementation of <code>IHttpClient</code> using <code>axios</code>. This is pretty straightforward using a <code>class</code> implementing <code>IHttpClient</code> interface and taking a look at <a href="https://axios-http.com/docs/instance"><code>axios</code>&#8216;s documentation</a>:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">class AxiosHttpClient implements IHttpClient {<br/>  private instance: AxiosInstance | null = null;<br/><br/>  private get axiosClient(): AxiosInstance {<br/>    return this.instance ?? this.initAxiosClient();<br/>  }<br/><br/>  private initAxiosClient() {<br/>    return axios.create();<br/>  }<br/><br/>  get&lt;TResponse&gt;(url: string): Promise&lt;TResponse&gt; {<br/>    return new Promise&lt;TResponse&gt;((resolve, reject) =&gt; {<br/>      this.axiosClient<br/>        .get&lt;TResponse, AxiosResponse&lt;TResponse&gt;&gt;(url)<br/>        .then((result) =&gt; {<br/>          resolve(result.data);<br/>        })<br/>        .catch((error: Error | AxiosError) =&gt; {<br/>          reject(error);<br/>        });<br/>    });<br/>  }<br/>}</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">httpClient.ts &#8211; AxiosHttpClient implementation (get only)</span> </div> </div></div>



<p class="wp-block-paragraph">This implementation lets us encapsulate a simple singleton inside the class.</p>



<p class="wp-block-paragraph">The last step here is to expose the instance of our HTTP client. Remember to <strong>always export the interface type variable</strong>:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">export const httpClient: IHttpClient = new AxiosHttpClient();</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">httpClient.ts &#8211; exporting AxiosHttpClient as IHttpClient singleton instance</span> </div> </div></div>



<p class="wp-block-paragraph">That&#8217;s basically how we wrap external libraries in TypeScript. Easy-peasy <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h3 class="wp-block-heading">Using the wrapper</h3>



<p class="wp-block-paragraph">I can now use our wrapper in <code>ProductsList.tsx</code> component:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-line="2,10-11" data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">import { useEffect, useState } from &quot;react&quot;;<br/>import { httpClient } from &quot;../wrappers/httpClient&quot;; // we don&#039;t import axios here anymore<br/>import { Product } from &quot;../types/product&quot;;<br/>import { DummyJsonProductsResult } from &quot;../types/dummyJsonProductsResult&quot;;<br/><br/>export const ProductsList = () =&gt; {<br/>  const [products, setProducts] = useState&lt;Product[] | null&gt;(null);<br/><br/>  useEffect(() =&gt; {<br/>    httpClient // instead of axios, we use our wrapper in components<br/>      .get&lt;DummyJsonProductsResult&gt;(&quot;https://dummyjson.com/products&quot;)<br/>      .then((result) =&gt; {<br/>        setProducts(result.data.products);<br/>      });<br/>  }, []);<br/> <br/> // ...<br/>};</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">ProductsList.tsx &#8211; using IHttpClient wrapper</span> </div> </div></div>



<p class="wp-block-paragraph">Notice how easy that was. Since now, we only import stuff from <code>axios</code> package in <code>httpClient.ts</code> file. Only this single file is dependent on <a href="https://www.npmjs.com/package/axios"><code>axios</code> npm package</a>. None of our components (and other project files) know about <code>axios</code>. Our IDE only knows that the wrapper is an object instance fulfilling <code>IHttpClient</code> contract:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" fetchpriority="high" decoding="async" width="537" height="332" data-attachment-id="4361" data-permalink="https://www.codejourney.net/how-and-why-to-wrap-external-libraries/1_usingwrapperinterface/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/1_UsingWrapperInterface.png?fit=537%2C332&amp;ssl=1" data-orig-size="537,332" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="1_UsingWrapperInterface" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/1_UsingWrapperInterface.png?fit=537%2C332&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/1_UsingWrapperInterface.png?resize=537%2C332&#038;ssl=1" alt="Interface-implementing wrapper instance usage in Visual Studio Code" class="wp-image-4361"/></figure>
</div>


<h3 class="wp-block-heading">Extra wrapper features</h3>



<p class="wp-block-paragraph">Apart from nicely isolating us from dependencies, wrappers have more advantages. One of them is a possibility to configure the library in a single place. In our example with <code>axios</code> &#8211; imagine that one day you want to add custom headers to each HTTP request. Having all API calls going via <code>AxiosHttpClient</code>, you can configure such things there, in a single place. That way, you follow the <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY principle</a> and keep all the logic related to <code>axios</code> (or to any other external dependency) in a single place. It also comes with benefits like easy testability etc.</p>



<p class="wp-block-paragraph">For clarity, I also added <code>post</code> support to our <code>IHttpClient</code>. You can <a href="https://github.com/dsibinski/codejourney/commit/200f31ba0c5483f3e834a5ec4cd82566887e3d98">check it here</a>.</p>



<h2 class="wp-block-heading">Replacing the wrapped library</h2>



<p class="wp-block-paragraph">Ok, it&#8217;s time to have our solution battle-tested. We have the HTTP client nicely wrapped and exposed as an instance of <code>IHttpClient</code>. However, we came to the conclusion that <code>axios</code> is not good enough, and we want to have it replaced with <code>fetch</code>.</p>



<p class="wp-block-paragraph">Remember that in the real web application, you would have hundreds or thousands of usages of <code>IHttpClient</code> instance. That&#8217;s where the power of wrappers comes into play <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f60e.png" alt="😎" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p class="wp-block-paragraph">So how do I make sure those thousands of usages will now use <code>fetch</code> instead of <code>axios</code>? That&#8217;s actually pretty straightforward. I&#8217;ll simply add a new class &#8211; <code>FetchHttpClient</code> implementing <code>IHttpClient</code> interface:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-line="4,23" data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">class FetchHttpClient implements IHttpClient {<br/>  get&lt;TResponse&gt;(url: string): Promise&lt;TResponse&gt; {<br/>    return new Promise&lt;TResponse&gt;((resolve, reject) =&gt; {<br/>      fetch(url)<br/>        .then((response) =&gt;<br/>          response<br/>            .json()<br/>            .then((responseJson) =&gt; {<br/>              resolve(responseJson as TResponse);<br/>            })<br/>            .catch((error: Error) =&gt; {<br/>              reject(`Response JSON parsing error: ${error}`);<br/>            })<br/>        )<br/>        .catch((error: Error) =&gt; {<br/>          reject(error);<br/>        });<br/>    });<br/>  }<br/><br/>  post&lt;TResponse&gt;(url: string, data?: object): Promise&lt;TResponse&gt; {<br/>    return new Promise&lt;TResponse&gt;((resolve, reject) =&gt; {<br/>      fetch(url, {<br/>        method: &quot;POST&quot;,<br/>        headers: {<br/>          &quot;Content-Type&quot;: &quot;application/json&quot;,<br/>        },<br/>        body: JSON.stringify(data),<br/>      })<br/>        .then((response) =&gt;<br/>          response<br/>            .json()<br/>            .then((responseJson) =&gt; {<br/>              resolve(responseJson as TResponse);<br/>            })<br/>            .catch((error: Error) =&gt; {<br/>              reject(`Response JSON parsing error: ${error}`);<br/>            })<br/>        )<br/>        .catch((error: Error) =&gt; {<br/>          reject(error);<br/>        });<br/>    });<br/>  }<br/>}</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">httpClient.ts &#8211; new FetchHttpClient using fetch for get and post</span> </div> </div></div>



<p class="wp-block-paragraph">For completion, I included <code>POST</code> here as well.</p>



<p class="wp-block-paragraph">The one last thing I have to do to make our new <code>FetchHttpClient</code> be used in the whole app in place of <code>AxiosHttpClient</code> is to change a single line with export:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">export const httpClient: IHttpClient = new FetchHttpClient(); // instead of new AxiosHttpClient()</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">httpClient.ts &#8211; AxiosHttpClient replaced with FetchHttpClient</span> </div> </div></div>



<p class="wp-block-paragraph">and that&#8217;s it! Our whole application now uses <code>fetch</code> for <code>GET</code> and <code>POST</code> HTTP requests <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> And it even still works <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f605.png" alt="😅" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h2 class="wp-block-heading">Summary and source code</h2>



<p class="wp-block-paragraph">I hope that now you see how important it is to wrap external libraries. We have seen that on JavaScript/TypeScript app example, but this is applicable to any programming language and framework. </p>



<p class="wp-block-paragraph">It&#8217;s always good to be as independent as possible of 3rd party stuff. Too many times I&#8217;ve been in a situation that some <code>npm</code> package is so extensively used in a project, directly in the source code in hundreds of places, that it cannot be replaced without spending several days on it. Creating wrappers forces us to think abstract, which is another great advantage.</p>



<p class="wp-block-paragraph">You can find the complete source code here: <a href="https://github.com/dsibinski/codejourney/tree/main/wrapping-external-libraries">https://github.com/dsibinski/codejourney/tree/main/wrapping-external-libraries</a></p>


<script>(function() {
	window.mc4wp = window.mc4wp || {
		listeners: [],
		forms: {
			on: function(evt, cb) {
				window.mc4wp.listeners.push(
					{
						event   : evt,
						callback: cb
					}
				);
			}
		}
	}
})();
</script><!-- Mailchimp for WordPress v4.13.0 - https://wordpress.org/plugins/mailchimp-for-wp/ --><form id="mc4wp-form-1" class="mc4wp-form mc4wp-form-2612" method="post" data-id="2612" data-name="Download a free guide form" ><div class="mc4wp-form-fields"><table bgcolor="#f2f6f5"><tr><td> <p><p>
    <label>
<h1 style="">
  <center>GET A FREE GUIDE <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f381.png" alt="🎁" class="wp-smiley" style="height: 1em; max-height: 1em;" /></center>
      </h1>        
      <h2 style="font-family: Helvetica">
        <center>16 STEPS TO BECOME <br/>.NET FULL STACK WEB DEVELOPER </br>IN 2025</center>
      </h2>
</p>
  <center><div>
	<input type="email" name="EMAIL" placeholder="Email address" required />
    <p>
    <input type="text" name="FNAME" placeholder="Your name"
    required="">
  </p>
  </div>
    <center>

	<center><input type="submit" value="DOWNLOAD THE FREE GUIDE" style="color: #7b1fa2; font-weight:bold; font-size: 20px" /></center>
<p style="font-size: 12px; font-style: italic;">After you sign up, I may be sending you some emails with additional free content from time to time.
<br/>No spam, only awesome stuff</p>
</p></td></tr></table>

</div><label style="display: none !important;">Leave this field empty if you're human: <input type="text" name="_mc4wp_honeypot" value="" tabindex="-1" autocomplete="off" /></label><input type="hidden" name="_mc4wp_timestamp" value="1781462972" /><input type="hidden" name="_mc4wp_form_id" value="2612" /><input type="hidden" name="_mc4wp_form_element_id" value="mc4wp-form-1" /><div class="mc4wp-response"></div></form><!-- / Mailchimp for WordPress Plugin -->
<p>The post <a href="https://www.codejourney.net/how-and-why-to-wrap-external-libraries/">How (And Why?) To Wrap External Libraries?</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/how-and-why-to-wrap-external-libraries/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4346</post-id>	</item>
		<item>
		<title>[.NET Internals 07] Unmanaged resources: finalization, fReachable queue and dispose pattern</title>
		<link>https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/</link>
					<comments>https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 05 Sep 2018 13:00:22 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[dotnet-internals]]></category>
		<guid isPermaLink="false">https://www.dsibinski.pl/?p=2779</guid>

					<description><![CDATA[<p>Today we&#8217;re going to see how unmanaged resources are handled by .NET, what are finalization and fReachable queues and what&#8217;s the garbage collector&#8217;s role in it. We&#8217;ll also get to know what is a dispose pattern and see how to implement it. Unmanaged resources and finalizers First of all we should all get familiar with what&#8230;</p>
<p>The post <a href="https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/">[.NET Internals 07] Unmanaged resources: finalization, fReachable queue and dispose pattern</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Today we&#8217;re going to see how unmanaged resources are handled by .NET, what are <em>finalization</em> and <em>fReachable queues</em> and what&#8217;s the garbage collector&#8217;s role in it. We&#8217;ll also get to know what is a <em>dispose pattern</em> and see how to implement it.<br />
<span id="more-2779"></span></p>
<h1>Unmanaged resources and finalizers</h1>
<p>First of all we should all get familiar with what <em>unmanaged resources</em> are. These ones can be files or folders on the disk, database connections, GUI elements or network resources. You can also think of them as some external elements we need to interact with in our applications through some protocol (e.g. database queries or file system manipulation methods). They&#8217;re called <em>unmanaged</em> not without a reason &#8211; <strong>any unmanaged resources accessed from .NET code will not be automatically cleaned by the garbage collector</strong>. That&#8217;s how they are <em>not(un)managed</em>.</p>
<p>Maybe you&#8217;ve heard about <a href="https://en.cppreference.com/w/cpp/language/destructor" target="_blank" rel="noopener">destructors in C++</a> &#8211; remember methods called after class&#8217;s name (like its constructor) starting with &#8216;~&#8217; character? This also exists in .NET, but it&#8217;s not what you&#8217;d expect from C++. In .NET, such methods are referred to as <strong>finalizers</strong>.</p>
<h2>Finalizers and destructors in .NET</h2>
<p>Nonetheless, you can define a finalizer in your class in one of the following ways:</p>
<p>&nbsp;</p>
<p><strong> Using &#8220;destructor-like&#8221; syntax:</strong></p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91695157" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-destructor_example-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Destructor_Example.cs content, created by dsibinski on 07:36PM on September 03, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Destructor_Example.cs">
<tr>
<td id="file-destructor_example-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-destructor_example-cs-LC1" class="blob-code blob-code-inner js-file-line">namespace UnmanagedResourcesTests</td>
</tr>
<tr>
<td id="file-destructor_example-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-destructor_example-cs-LC2" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-destructor_example-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-destructor_example-cs-LC3" class="blob-code blob-code-inner js-file-line">    class MyTestClass</td>
</tr>
<tr>
<td id="file-destructor_example-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-destructor_example-cs-LC4" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-destructor_example-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-destructor_example-cs-LC5" class="blob-code blob-code-inner js-file-line">        ~MyTestClass()</td>
</tr>
<tr>
<td id="file-destructor_example-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-destructor_example-cs-LC6" class="blob-code blob-code-inner js-file-line">        {</td>
</tr>
<tr>
<td id="file-destructor_example-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-destructor_example-cs-LC7" class="blob-code blob-code-inner js-file-line">            Console.WriteLine(&quot;Finalizing my object!&quot;);</td>
</tr>
<tr>
<td id="file-destructor_example-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-destructor_example-cs-LC8" class="blob-code blob-code-inner js-file-line">        }</td>
</tr>
<tr>
<td id="file-destructor_example-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-destructor_example-cs-LC9" class="blob-code blob-code-inner js-file-line">    }</td>
</tr>
<tr>
<td id="file-destructor_example-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-destructor_example-cs-LC10" class="blob-code blob-code-inner js-file-line">}</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/c50e995d8697d7b27412789647abb372/raw/da9dc7058cfc1b1ccb57b878d2a4def0760ed953/Destructor_Example.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/c50e995d8697d7b27412789647abb372#file-destructor_example-cs" class="Link--inTextBlock"><br />
          Destructor_Example.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p><strong>Using Finalize() method:</strong></p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91695262" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-finalizer_example-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Finalizer_Example.cs content, created by dsibinski on 07:44PM on September 03, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Finalizer_Example.cs">
<tr>
<td id="file-finalizer_example-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-finalizer_example-cs-LC1" class="blob-code blob-code-inner js-file-line">namespace UnmanagedResourcesTests</td>
</tr>
<tr>
<td id="file-finalizer_example-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-finalizer_example-cs-LC2" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-finalizer_example-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-finalizer_example-cs-LC3" class="blob-code blob-code-inner js-file-line">    class MyTestClass</td>
</tr>
<tr>
<td id="file-finalizer_example-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-finalizer_example-cs-LC4" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-finalizer_example-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-finalizer_example-cs-LC5" class="blob-code blob-code-inner js-file-line">        void Finalize()</td>
</tr>
<tr>
<td id="file-finalizer_example-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-finalizer_example-cs-LC6" class="blob-code blob-code-inner js-file-line">        {</td>
</tr>
<tr>
<td id="file-finalizer_example-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-finalizer_example-cs-LC7" class="blob-code blob-code-inner js-file-line">            Console.WriteLine(&quot;Finalizing my object!&quot;);</td>
</tr>
<tr>
<td id="file-finalizer_example-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-finalizer_example-cs-LC8" class="blob-code blob-code-inner js-file-line">        }</td>
</tr>
<tr>
<td id="file-finalizer_example-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-finalizer_example-cs-LC9" class="blob-code blob-code-inner js-file-line">    }</td>
</tr>
<tr>
<td id="file-finalizer_example-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-finalizer_example-cs-LC10" class="blob-code blob-code-inner js-file-line">}</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/a5becab104ef57f2c8c35d8f9c66b672/raw/c1b3c742398d331530cf161a2aad242a4b65dcad/Finalizer_Example.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/a5becab104ef57f2c8c35d8f9c66b672#file-finalizer_example-cs" class="Link--inTextBlock"><br />
          Finalizer_Example.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>If you examine the IL code of both versions, it turns out that the <strong>destructor can be seen as a syntax sugar for the finalizer</strong>. In fact, the <span style="color: #ff6600;">~MyTestClass()</span> method is translated into <span style="color: #ff6600;">Finalize()</span> method:</p>
<p><figure id="attachment_2781" aria-describedby="caption-attachment-2781" style="width: 698px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizeIL.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" decoding="async" data-attachment-id="2781" data-permalink="https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/finalizeil/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizeIL.png?fit=698%2C648&amp;ssl=1" data-orig-size="698,648" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="FinalizeIL" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizeIL.png?fit=698%2C648&amp;ssl=1" class="wp-image-2781 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizeIL.png?resize=698%2C648&#038;ssl=1" alt="" width="698" height="648" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizeIL.png?w=698&amp;ssl=1 698w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizeIL.png?resize=300%2C279&amp;ssl=1 300w" sizes="(max-width: 698px) 100vw, 698px" /></a><figcaption id="caption-attachment-2781" class="wp-caption-text"><span style="font-size: 8pt;">Destructor translated into Finalize() in IL</span></figcaption></figure></p>
<p>The only difference is that &#8211; as you can see on the IL above &#8211; <span style="color: #ff6600;">Finalize()</span> method created by the compiler from the destructor is implicitly calling the <span style="color: #ff6600;">Finalize()</span> method on the base class of the object (you can see it in the <span style="color: #ff6600;">finally</span> block in the IL generated). So in case of using a destructor-like syntax, we are actually creating a finalizer by overriding <span style="color: #ff6600;">Finalize()</span> method, whereas when implementing a <span style="color: #ff6600;">Finalize()</span> method directly we do it as we&#8217;d use the <span style="color: #ff6600;">new</span> keyword (hiding base class&#8217;s implementation of <span style="color: #ff6600;">Finalize()</span> method).</p>
<h2>Will GC call the finalizer for me?</h2>
<p>As you may know, finalizers methods are normally used to clean-up some unmanaged resources (e.g. to release a file handle or database connection). You may think that as soon as your object is ready to be collected (nothing references it anymore), garbage collector will firstly call the finalizer (to ensure everything is cleaned up) and then reclaim the memory used by the object.</p>
<p><strong>Unfortunately not</strong>. If you think about it one more time &#8211; GC cannot know what&#8217;s inside your <span style="color: #ff6600;">Finalize()</span> method. You can put there the code which downloads the whole Internet just like that:</p>
<p><figure id="attachment_2784" aria-describedby="caption-attachment-2784" style="width: 490px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/WholeInternet.gif?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" decoding="async" data-attachment-id="2784" data-permalink="https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/wholeinternet/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/WholeInternet.gif?fit=490%2C260&amp;ssl=1" data-orig-size="490,260" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="WholeInternet" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/WholeInternet.gif?fit=490%2C260&amp;ssl=1" class="wp-image-2784 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/WholeInternet.gif?resize=490%2C260&#038;ssl=1" alt="" width="490" height="260" /></a><figcaption id="caption-attachment-2784" class="wp-caption-text"><a href="https://knowyourmeme.com/photos/53057-the-last-page-of-the-internet" target="_blank" rel="noopener"><span style="font-size: 8pt;">Source</span></a></figcaption></figure></p>
<p>&#8230; and even though we have nowadays a bit faster bandwidths than the one from the gif <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> , you can clearly see it wouldn&#8217;t be a good idea to block garbage collection because of some costly process being executed before the memory for the object is reclaimed.</p>
<p>In order to avoid the above-described scenario, which would slow down the GC&#8217;s work significantly, .NET contributors decided that the <strong>finalizers on the objects are called periodically on a separate thread, completely independently from the GC</strong>.</p>
<p>This way the main GC thread is not blocked. However, it adds a bit of complexity to the garbage collection process &#8211; continue reading for more details.</p>
<h1>Finalization mechanism</h1>
<p>As we said in <a href="https://www.codejourney.net/2018/08/net-internals-05-garbage-collection-marking-collection-and-heaps-compaction/" target="_blank" rel="noopener">one of the previous posts</a>, one of the various sources of references to objects in our .NET application (GC roots) are &#8220;objects finalization references&#8221;. Let&#8217;s now make this mysterious term clear.</p>
<p>&nbsp;</p>
<p>In order to prevent having a finalizable object (containing finalizer method) reclaimed before its <span style="color: #ff6600;">Finalize()</span> method is called (which happens independently from the GC as you already know), there&#8217;s a separate references list called <strong>finalization queue </strong>maintained by the GC. As soon as memory for a new finalizable object is allocated, a reference to it is also put on the finalization queue, which becomes a <em>finalization root</em> for this object (it&#8217;s not the same kind of root as &#8220;normal&#8221; GC roots &#8211; it&#8217;s treated a bit more differently).</p>
<p>The diagram below presents the memory state just after few new objects were allocated on the managed heap.</p>
<p><figure id="attachment_2790" aria-describedby="caption-attachment-2790" style="width: 504px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue1-1.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2790" data-permalink="https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/finalizationfreachablequeue1-2/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue1-1.png?fit=504%2C398&amp;ssl=1" data-orig-size="504,398" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="FinalizationFreachableQueue1" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue1-1.png?fit=504%2C398&amp;ssl=1" class="wp-image-2790 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue1-1.png?resize=504%2C398&#038;ssl=1" alt="" width="504" height="398" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue1-1.png?w=504&amp;ssl=1 504w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue1-1.png?resize=300%2C237&amp;ssl=1 300w" sizes="auto, (max-width: 504px) 100vw, 504px" /></a><figcaption id="caption-attachment-2790" class="wp-caption-text"><span style="font-size: 8pt;">Finalization and fReachable queues before GC, <a href="https://www.dotnettricks.com/learn/netframework/net-garbage-collection-and-finalization-queue" target="_blank" rel="noopener">source</a></span></figcaption></figure></p>
<p>As you can see, objects <em>ob2</em>, <em>ob3</em>, <em>ob5</em>, <em>ob6</em> and <em>ob10 </em>are all placed on the finalization queue, which means all of them contain <span style="color: #ff6600;">Finalize()</span> method.</p>
<p>Within these objects, <em>ob2</em> and <em>ob5</em> don&#8217;t have any references (roots) &#8211; it&#8217;s visible on the left side (heap). It means that these two objects are not used (are not referenced by anything) so they&#8217;re ready to be garbage collected. However, each of them contains a finalization root on the finalization queue.</p>
<p>As soon as the next garbage collection occurs, <em>ob2</em> and <em>ob5</em> cannot be reclaimed straightaway, as there&#8217;s a <span style="color: #ff6600;">Finalize()</span> method to be called on them first. Instead, when GC examines these two objects, it sees that they are not referenced from &#8220;normal&#8221; roots, but they have finalization references on the finalization queue. If that&#8217;s the case, GC moves finalization reference to another data structure called <strong>fReachable queue </strong>(also visible on the diagram above).</p>
<p>After, both queues and the heap look as follows:</p>
<p><figure id="attachment_2791" aria-describedby="caption-attachment-2791" style="width: 496px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue2.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2791" data-permalink="https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/finalizationfreachablequeue2/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue2.png?fit=496%2C386&amp;ssl=1" data-orig-size="496,386" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="FinalizationFreachableQueue2" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue2.png?fit=496%2C386&amp;ssl=1" class="wp-image-2791 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue2.png?resize=496%2C386&#038;ssl=1" alt="" width="496" height="386" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue2.png?w=496&amp;ssl=1 496w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue2.png?resize=300%2C233&amp;ssl=1 300w" sizes="auto, (max-width: 496px) 100vw, 496px" /></a><figcaption id="caption-attachment-2791" class="wp-caption-text"><span style="font-size: 8pt;">Finalization and fReachable queues after GC, <a href="https://www.dotnettricks.com/learn/netframework/net-garbage-collection-and-finalization-queue" target="_blank" rel="noopener">source</a></span></figcaption></figure></p>
<p>That&#8217;s what I meant by stating that finalization roots are &#8220;special&#8221; kind of GC roots. Apart from that, <em>ob2</em> and <em>ob5</em> are still seen as &#8220;rooted&#8221; (as still being referenced) and because of that are not reclaimed by the GC. In that moment, standard <a href="https://www.codejourney.net/2018/08/net-internals-06-generational-garbage-collection/" target="_blank" rel="noopener">generational GC rules</a> apply, so if the collection below was a gen 1 collection, both objects will be promoted to gen 2.</p>
<p>Periodically, the finalization runs on a separate thread exploring the fReachable queue and calling <span style="color: #ff6600;">Finalize()</span> method on each object referenced from it. Then it removes the reference to this object from the queue. At this moment, finalizable object becomes rootless and can be reclaimed in the next garbage collection cycle.</p>
<h1>Dispose for the rescue</h1>
<p>In order to unify usage of finalizers and allow developers to correctly free their resources without unnecessarily prolonging their objects&#8217; lifetime (as you saw above, finalizable objects stay uncollected for at least 1 more GC round than &#8220;normal&#8221; objects), programmer can (and should) implement a <strong><em>dispose pattern</em></strong>. The purpose of it is <strong>to allow the developer to free unmanaged resources &#8220;manually&#8221; as soon as they are not needed anymore</strong>.</p>
<p>&nbsp;</p>
<p>The framework also provides a <span style="color: #ff6600;"><a style="color: #ff6600;" href="https://docs.microsoft.com/en-us/dotnet/api/system.gc.suppressfinalize?view=netframework-4.7.2" target="_blank" rel="noopener">GC.SuppressFinalize</a></span> method which tells GC that the object has been manually disposed and no more finalization is necessary. As soon as it&#8217;s called, the object reference is removed from finalization/fReachable queue. The goal is to prevent finalizing the object twice.</p>
<h2>IDisposable</h2>
<p>.NET Framework provides a <a href="https://docs.microsoft.com/en-us/dotnet/api/system.idisposable?view=netframework-4.7.2" target="_blank" rel="noopener">System.IDisposable</a> interface which should be implemented by a class which works with unmanaged resources.</p>
<p>Sample implementation of dispose pattern can look as follows:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91713758" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-dispose_example-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Dispose_example.cs content, created by dsibinski on 06:58PM on September 04, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Dispose_example.cs">
<tr>
<td id="file-dispose_example-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-dispose_example-cs-LC1" class="blob-code blob-code-inner js-file-line">public class UnmanagedClass : IDisposable</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-dispose_example-cs-LC2" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-dispose_example-cs-LC3" class="blob-code blob-code-inner js-file-line">    public void Dispose()</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-dispose_example-cs-LC4" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-dispose_example-cs-LC5" class="blob-code blob-code-inner js-file-line">        CleanUp(true);</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-dispose_example-cs-LC6" class="blob-code blob-code-inner js-file-line">        GC.SuppressFinalize(this);</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-dispose_example-cs-LC7" class="blob-code blob-code-inner js-file-line">    }</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-dispose_example-cs-LC8" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-dispose_example-cs-LC9" class="blob-code blob-code-inner js-file-line">    private void CleanUp(bool disposing)</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-dispose_example-cs-LC10" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-dispose_example-cs-LC11" class="blob-code blob-code-inner js-file-line">        if (disposing)</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-dispose_example-cs-LC12" class="blob-code blob-code-inner js-file-line">        {</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-dispose_example-cs-LC13" class="blob-code blob-code-inner js-file-line">            // any thread-specific cleanup code</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
<td id="file-dispose_example-cs-LC14" class="blob-code blob-code-inner js-file-line">        }</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
<td id="file-dispose_example-cs-LC15" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
<td id="file-dispose_example-cs-LC16" class="blob-code blob-code-inner js-file-line">        // cleaning unmanaged resources here</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
<td id="file-dispose_example-cs-LC17" class="blob-code blob-code-inner js-file-line">    }</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
<td id="file-dispose_example-cs-LC18" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L19" class="blob-num js-line-number js-blob-rnum" data-line-number="19"></td>
<td id="file-dispose_example-cs-LC19" class="blob-code blob-code-inner js-file-line">    public void Finalize()</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L20" class="blob-num js-line-number js-blob-rnum" data-line-number="20"></td>
<td id="file-dispose_example-cs-LC20" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L21" class="blob-num js-line-number js-blob-rnum" data-line-number="21"></td>
<td id="file-dispose_example-cs-LC21" class="blob-code blob-code-inner js-file-line">        CleanUp(false);</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L22" class="blob-num js-line-number js-blob-rnum" data-line-number="22"></td>
<td id="file-dispose_example-cs-LC22" class="blob-code blob-code-inner js-file-line">    }</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L23" class="blob-num js-line-number js-blob-rnum" data-line-number="23"></td>
<td id="file-dispose_example-cs-LC23" class="blob-code blob-code-inner js-file-line">}</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/2c51fc4c0f2df3ec9c4c69efd6f3bb7b/raw/125032117302184cabb58e8d8a0ca9a96b80405b/Dispose_example.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/2c51fc4c0f2df3ec9c4c69efd6f3bb7b#file-dispose_example-cs" class="Link--inTextBlock"><br />
          Dispose_example.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>Implementing <span style="color: #ff6600;">IDisposable</span> interface only forces us to add <span style="color: #ff6600;">Dispose()</span> method. Inside, we perform the resources clean-up and call <span style="color: #ff6600;">GC.SuppressFinalize(this)</span> to mark our object as finalized. We also implemented a separate method, in the example called <span style="color: #ff6600;">CleanUp(bool disposing)</span>, which performs the actual releasing of unmanaged resources. But why do we need this <span style="color: #ff6600;">bool disposing</span> parameter?</p>
<p>&nbsp;</p>
<p>It may be important to differentiate when the resources cleanup is called directly from code (we&#8217;ll see how it can be done in the next section) or by the finalization thread. As you already know, finalization is executed periodically <strong>on a separate thread</strong>. It means that if our <span style="color: #ff6600;">UnmanagedClass</span> needs any thread-specific resources cleanup, it&#8217;s not a good idea to execute it on totally independent, finalization thread, which is out-of-context at that moment.</p>
<p>That&#8217;s why we added a boolean parameter to the <span style="color: #ff6600;">CleanUp</span> method, which will be set to &#8220;true&#8221; as soon as <span style="color: #ff6600;">Dispose()</span> method is called directly from code. In that case we know that we can execute thread-specific cleanup code.</p>
<p>Additionally, we implemented the <span style="color: #ff6600;">Finalize()</span> method, which also calls <span style="color: #ff6600;">CleanUp()</span>, but passing &#8220;false&#8221; parameter&#8217;s value. In that case, as the finalization thread is out-of-context, we shouldn&#8217;t execute thread-specific cleanup code. We should treat <span style="color: #ff6600;">Finalize()</span> method as a last resort in case <span style="color: #ff6600;">Dispose()</span> has not been called because of some reason.</p>
<p>You can also check <a href="https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose" target="_blank" rel="noopener">Microsoft dosc</a> to see what&#8217;s their recommendation on implementing IDisposable interface.</p>
<h2>Using statement</h2>
<p>As mentioned above, the programmer can explicitly call <span style="color: #ff6600;">Dispose()</span> method on the class:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91714024" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-dispose_manually-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Dispose_manually.cs content, created by dsibinski on 07:10PM on September 04, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Dispose_manually.cs">
<tr>
<td id="file-dispose_manually-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-dispose_manually-cs-LC1" class="blob-code blob-code-inner js-file-line">  UnmanagedClass myClass = new UnmanagedClass();</td>
</tr>
<tr>
<td id="file-dispose_manually-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-dispose_manually-cs-LC2" class="blob-code blob-code-inner js-file-line">  // working with the instance&#8230;</td>
</tr>
<tr>
<td id="file-dispose_manually-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-dispose_manually-cs-LC3" class="blob-code blob-code-inner js-file-line">  myClass.Dispose();</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/e8d933cf16b9a09aff19a97de6fc32ce/raw/78b5351e222055e3124a0eae88ad4b75fd0b6b56/Dispose_manually.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/e8d933cf16b9a09aff19a97de6fc32ce#file-dispose_manually-cs" class="Link--inTextBlock"><br />
          Dispose_manually.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>but there&#8217;s another &#8211; and preferred &#8211; way: wrapping usage of the class within <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement" target="_blank" rel="noopener">using</a> statement:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91714058" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-dispose_with_using-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Dispose_with_using.cs content, created by dsibinski on 07:12PM on September 04, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Dispose_with_using.cs">
<tr>
<td id="file-dispose_with_using-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-dispose_with_using-cs-LC1" class="blob-code blob-code-inner js-file-line">  using (UnmanagedClass myClass = new UnmanagedClass())</td>
</tr>
<tr>
<td id="file-dispose_with_using-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-dispose_with_using-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-dispose_with_using-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-dispose_with_using-cs-LC3" class="blob-code blob-code-inner js-file-line">      // working with the instance&#8230;</td>
</tr>
<tr>
<td id="file-dispose_with_using-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-dispose_with_using-cs-LC4" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/aba29f9bdf87bc129be4948e1e4c9995/raw/53e114999bbaeec03f5fdfc9eb5b29848f0fb882/Dispose_with_using.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/aba29f9bdf87bc129be4948e1e4c9995#file-dispose_with_using-cs" class="Link--inTextBlock"><br />
          Dispose_with_using.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>How does <span style="color: #ff6600;">using</span> statement ensure that <span style="color: #ff6600;">Dispose()</span> is called on our object created within it?</p>
<p>Let&#8217;s see the IL:</p>
<p><figure id="attachment_2792" aria-describedby="caption-attachment-2792" style="width: 745px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/using_IL.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2792" data-permalink="https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/using_il/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/using_IL.png?fit=745%2C763&amp;ssl=1" data-orig-size="745,763" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="using_IL" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/using_IL.png?fit=745%2C763&amp;ssl=1" class="wp-image-2792 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/using_IL.png?resize=745%2C763&#038;ssl=1" alt="" width="745" height="763" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/using_IL.png?w=745&amp;ssl=1 745w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/using_IL.png?resize=293%2C300&amp;ssl=1 293w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/using_IL.png?resize=720%2C737&amp;ssl=1 720w" sizes="auto, (max-width: 745px) 100vw, 745px" /></a><figcaption id="caption-attachment-2792" class="wp-caption-text"><span style="font-size: 8pt;">IL of <span style="color: #ff6600;">using</span> statement</span></figcaption></figure></p>
<p>As you can see, the compiler translates <span style="color: #ff6600;">using</span> statement into try-finally block. In the <span style="color: #ff6600;">finally</span> part <span style="color: #ff6600;">Dispose()</span> method is called on our object&#8217;s instance.</p>
<p>This way the compiler ensures that even if there&#8217;s any exception thrown in the <span style="color: #ff6600;">using</span> block, the object will be disposed. That&#8217;s why we should always work with objects that may use unmanaged resources in such a way.</p>
<h1>Summary</h1>
<p>In this 7th post from <a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener">.NET Internals</a> series we examined how unmanaged resources are handled within .NET Framework and what&#8217;s the GC&#8217;s role in that process. We got to know two new GC-internal data structures: finalization and fReachable queues. In the end, we got familiar with dispose pattern and <span style="color: #ff6600;">using</span> statement.</p>
<p>I hope it helped you to clarify these topics a bit <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>See you next week! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p><script>(function() {
	window.mc4wp = window.mc4wp || {
		listeners: [],
		forms: {
			on: function(evt, cb) {
				window.mc4wp.listeners.push(
					{
						event   : evt,
						callback: cb
					}
				);
			}
		}
	}
})();
</script><!-- Mailchimp for WordPress v4.13.0 - https://wordpress.org/plugins/mailchimp-for-wp/ --><form id="mc4wp-form-2" class="mc4wp-form mc4wp-form-2612" method="post" data-id="2612" data-name="Download a free guide form" ><div class="mc4wp-form-fields"><table bgcolor="#f2f6f5"><tr><td> <p><p>
    <label>
<h1 style="">
  <center>GET A FREE GUIDE <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f381.png" alt="🎁" class="wp-smiley" style="height: 1em; max-height: 1em;" /></center>
      </h1>        
      <h2 style="font-family: Helvetica">
        <center>16 STEPS TO BECOME <br/>.NET FULL STACK WEB DEVELOPER </br>IN 2025</center>
      </h2>
</p>
  <center><div>
	<input type="email" name="EMAIL" placeholder="Email address" required />
    <p>
    <input type="text" name="FNAME" placeholder="Your name"
    required="">
  </p>
  </div>
    <center>

	<center><input type="submit" value="DOWNLOAD THE FREE GUIDE" style="color: #7b1fa2; font-weight:bold; font-size: 20px" /></center>
<p style="font-size: 12px; font-style: italic;">After you sign up, I may be sending you some emails with additional free content from time to time.
<br/>No spam, only awesome stuff</p>
</p></td></tr></table>

</div><label style="display: none !important;">Leave this field empty if you're human: <input type="text" name="_mc4wp_honeypot" value="" tabindex="-1" autocomplete="off" /></label><input type="hidden" name="_mc4wp_timestamp" value="1781462975" /><input type="hidden" name="_mc4wp_form_id" value="2612" /><input type="hidden" name="_mc4wp_form_element_id" value="mc4wp-form-2" /><div class="mc4wp-response"></div></form><!-- / Mailchimp for WordPress Plugin --></p>
<p>The post <a href="https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/">[.NET Internals 07] Unmanaged resources: finalization, fReachable queue and dispose pattern</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/feed/</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2779</post-id>	</item>
	</channel>
</rss>
