Disposable Pattern in .NET

Garbage collector (GC) is a blessing in .NET, if you happen to program in C++ in the past, where it was one of the prime responsibility of a developer was to manage the heap. That means when ever an object is created on the heap, it has to be deleted in the corresponding method or in the destructor, if the life is object long. And if he/she forgot to do so, then the nightmare begins in the form of memory leaks and troubleshooting may take hours and some times even days. But that's the story of the past, we as a C# developers are blessed, because we have a world class Garbage Collector comes right out of the box with .NET framework and an integral part of the CLR. What does it mean?? That means we need not to worry about deleting/disposing the objects being created on the heap, and GC, at runtime manage the heap, and its robust algorithm sees when some object is no longer needed, it silently dispose it off. Very clever, but you know what, not that clever. It doesn't know how to close the resources like a Database connections,  file handle when it is no more needed, doesn't know what to do when the Network connection needs to be released or closed etc. etc. First thing that would come into your mind, why don't we use the finalizer/destructor to take care of this scenario?? Like we close these resource handles in the finalizers, how's that?? You can do so, but it will not work, why?? due to the GC’s non-deterministic behavior, it may take longer than expected that the destructor/finalizer will be called, and there will be a deadlock, that is you might need to reuse some resource, and since the objects destructor is not called, the object is not releasing it, you are stuck, complete deadlock. So what we do now?? Good news is, you can do it elegantly with the help of proper usage of Disposable Pattern, which is nothing more than implementation of Template Design Pattern (GOF). Before going into the details of the pattern, lets first take a look at what are disposable objects and how the .NET framework facilitates us in this regard.

IDisposable Objects

It is recommended that any custom object that has acquired or owns system/native resources should implement IDisposable interface in order to participate in the disposable mechanism. What does that mean?? Does the CLR will  take care of disposing the object automatically. Not really, it is the consumers responsibility to call the Dispose method, as soon as the object is no more needed. .NET framework itself has created many disposable classes as shown in Figure-1. All of these classes if you look at them are responsible for interacting system resources, like memory, file system, network stream, pipes etc. etc. That's why they all are implemented the IDisposable interface, so the consumer of these types should be aware of its usage and release them as soon as they are done.

ClassDiagram2 Figure 1

Here is one i am using as an example, StringWriter:-

Code Snippet
  1. public static class TXmlUtils<T> where T : class
  2. {
  3.     public static string ToString2(T context)
  4.     {
  5.         string xmlString = string.Empty;
  6.         StringWriter stringWriter = new StringWriter();
  7.         try
  8.         {
  9.             XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
  10.             xmlSerializer.Serialize(stringWriter, context);
  11.             xmlString = stringWriter.ToString();
  12.         }
  13.         finally
  14.         {
  15.             IDisposable disposable = stringWriter as IDisposable;
  16.             if (disposable != null)
  17.             {
  18.                 disposable.Dispose();
  19.             }
  20.         }
  21.  
  22.         return xmlString;
  23.     }

This is a generic method as you can see,converts a generic context object into Xml string. It does this with the help of an IDisposable class StringWriter. When it is done {using} it, disposes it off in the finally block, that actually releases all the resources StringWriter is holding off. It is so common in .NET that it provides a keyword {using} to encapsulate this scenario. Here is a rewrite of the above method: The {using} when expanded by the pre-compiler/compiler, takes the above mentioned form.

Code Snippet
  1. public static string ToString(T context)
  2.         {
  3.             string xmlString = string.Empty;
  4.             using (StringWriter stringWriter = new StringWriter())
  5.             {
  6.                 XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
  7.                 xmlSerializer.Serialize(stringWriter, context);
  8.                 xmlString = stringWriter.ToString();
  9.             }
  10.             return xmlString;
  11.         }

As you may have noticed by now, that the implementation of IDisposible has nothing to do with Garbage Collector’s cleanup mechanism. It is the consumer’s duty to dispose off the object. But the finalizer / destructor do get called by the Garbage Collector for final cleanup, the only problem is, the destruction process is non-deterministic. That's why when you are disposing an object you should take care of finalizer too that is if something needs to be disposed at the very end like un-managed resources, when implementing IDisposable and that's how a Disposable pattern get evolved, that is nothing more than proper implimentation of IDisposable interface especially where class derivatives are involved.

Disposable Pattern and Its Implementation 

Take a look at the following figure (Figure-2), the Disposable pattern is very simple. The consumer/client consumes  an IDisposable based class and calls the Dispose method, when it is done using it, that's it. No more no less. The only thing is how these Dispose methods are being implemented internally, that is the crux of this pattern. Question then arises, Is the Disposable Pattern is a design pattern or its just an implementation/coding pattern. ? You are the better judge But it is for sure, If you look at it closely, it actually uses “Template Design Pattern”, for its implementation.

 disposable pattern Figure-2

As you can see from the Class Model (Figure-2) and the Sequence Diagram (Figure-3A), DisposableBase is IDisposable, and implements the Dispose() method. The Dispose() method further calls two methods, Dispose(true) and GC.SuppressFinalize(this) methods. Dispose(bool) is actually a virtual method, provides extensibility for the derived ones to implement their disposing mechanism. This Dispose(.) method when called with a true parameter, disposes all the resources, managed as well as un-managed/native ones. And when it is called with a false parameter, only disposes the un-managed resources. Dispose() method also calls GC.SuppressFinalize(this), that actually tells the Garbage Collector (GC) not to call Finalizer/Destructor (~DisposableBase). 

sequence2sequence3

Figure-3A  -- Figure-3B

Here is the implementation of the Disposable pattern in C#:

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace Shams.DisposablePattern
  7. {
  8.     public abstract class DisposableBase : IDisposable
  9.     {
  10.         public DisposableBase() { }
  11.  
  12.         /// <summary>
  13.         /// Destructor/Finalizer, releases native resources
  14.         /// </summary>
  15.         ~DisposableBase()
  16.         {
  17.             // Virtual Dispose called..
  18.             Dispose(false);
  19.  
  20.             System.Diagnostics.Trace.WriteLine("DisposableBase.Finalizer called...");
  21.         }
  22.  
  23.         #region IDisposable Members
  24.  
  25.         public void Dispose()
  26.         {
  27.             this.Dispose(true);
  28.             
  29.             // Tell GC not to call the Finalizer/Destructor...
  30.             GC.SuppressFinalize(this);
  31.         }
  32.  
  33.         #endregion
  34.  
  35.         protected virtual void Dispose(bool disposing)
  36.         {
  37.             if (disposing)
  38.             {
  39.                 // Free other state (managed objects).
  40.  
  41.                 System.Diagnostics.Trace.WriteLine("DisposableBase.Dispose(disposing)/managed called...");
  42.             }
  43.             // Free your own state (unmanaged objects).
  44.             // Set large fields to null.
  45.             try
  46.             {
  47.                 System.Diagnostics.Trace.WriteLine("DisposableBase.Dispose(disposing)/un-managed called...");
  48.             }
  49.             catch (Exception ex)
  50.             {
  51.                 System.Diagnostics.Trace.WriteLine(ex.ToString());
  52.             }
  53.         }
  54.  
  55.         public abstract void DoSomeWork();
  56.     }
  57. }

Figure-4

Note that even if we have an explicit mechanism in place, that is the Dispose() method, we also provide an implicit mechanism too in the form of Finalizer/Destructor as a backup to prevent from memory leakage of any un-managed/native resources, by calling Dispose(false) to clean them up. So just in case if the consumer fails to call Dispose() method, these resources will eventually be cleaned up by the GC {Please Ref.: (lines 15-20 above) and the the sequence diagram (Figure-3B)}.

Now, take a look at the following derived class, where we are only overriding the Dispose(bool) method (lines 25-43), when it is done disposing its own resources, disposes the base ones by calling base.Dispose(bool).

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace Shams.DisposablePattern
  7. {
  8.     public class DisposableDerived : DisposableBase
  9.     {
  10.         public DisposableDerived() { }
  11.  
  12.         /// <summary>
  13.         /// Destructor/Finalizer, releases native resources
  14.         /// </summary>
  15.         ~DisposableDerived()
  16.         {
  17.             // Commented, No need of it, the base class takes care of it
  18.             //Dispose(false);
  19.  
  20.             System.Diagnostics.Trace.WriteLine("DisposableDerived.Finalizer called...");
  21.         }
  22.  
  23.         #region IDisposable Overrides
  24.  
  25.         protected override void Dispose(bool disposing)
  26.         {
  27.             try
  28.             {
  29.                 if (disposing)
  30.                 {
  31.                     // Clean up managed resources
  32.  
  33.                     System.Diagnostics.Trace.WriteLine("DisposableDerived.Dispose(disposing)/managed called...");
  34.                 }
  35.  
  36.                 // Clean up native/un-managed resources
  37.                 System.Diagnostics.Trace.WriteLine("DisposableDerived.Dispose(disposing)/unmanaged called...");
  38.             }
  39.             finally
  40.             {
  41.                 // finally, dispose the base one...
  42.                 base.Dispose(disposing);
  43.             }
  44.         }
  45.         #endregion
  46.  
  47.         public override void DoSomeWork()
  48.         {
  49.             System.Diagnostics.Trace.WriteLine("Some Work Done...");
  50.         }
  51.     }
  52. }

Figure-5

Lets now take a look at the Consumer. The consumer, creates an IDispoasble based concrete class, DisposableDerived, and when some useful work is done, the in-built {Using} mechanism disposes it off, by calling DisposableDerived.Dispose(). Here is the sequence diagram for it (Figure-6):

sequence1 Figure-6

And here is the corresponding implementation of it in C#. You can see from the output (lines 19- 23, Figure-7) that all the Disposables are called properly.

Code Snippet
  1.  
  2. using System;
  3. namespace Shams.DisposablePattern
  4. {
  5.     public class Consumer
  6.     {
  7.         public IDisposable disposable;
  8.  
  9.         public Consumer() { }
  10.  
  11.         public static void Main(string[] args)
  12.         {
  13.             using (DisposableBase disposable = new DisposableDerived())
  14.             {
  15.                 disposable.DoSomeWork();
  16.             }
  17.  
  18.             /* Output is:
  19.              *  Some Work Done...
  20.                 DisposableDerived.Dispose(disposing)/managed called...
  21.                 DisposableDerived.Dispose(disposing)/unmanaged called...
  22.                 DisposableBase.Dispose(disposing)/managed called...
  23.                 DisposableBase.Dispose(disposing)/un-managed called...
  24.             */
  25.  
  26.             /* Output, If you comment out the
  27.              * GC.SuppressFinalize(this); from the DisposableBase.Dispose() method
  28.                 
  29.                 Some Work Done...
  30.                 DisposableDerived.Dispose(disposing)/managed called...
  31.                 DisposableDerived.Dispose(disposing)/unmanaged called...
  32.                 DisposableBase.Dispose(disposing)/managed called...
  33.                 DisposableBase.Dispose(disposing)/un-managed called...
  34.                 
  35.                 The thread 0x3f0 has exited with code 0 (0x0).
  36.                 The thread 0x2134 has exited with code 0 (0x0).
  37.                 
  38.                 DisposableDerived.Finalizer called...
  39.                 DisposableDerived.Dispose(disposing)/unmanaged called...
  40.                 DisposableBase.Dispose(disposing)/un-managed called...
  41.                 DisposableBase.Finalizer called...
  42.              */
  43.         }
  44.     }//end Consumer
  45. }

Figure-7

When you run the app, you’ll see the output as shown above (lines 19-23). Just in case you, comment out the GC.SuppressFinalize(.) method from the base class, you’ll notice that the Finalizer is called, that actually disposes of the un-manged or native resources (see lines 26-41 above). With all said here is a reference for further exploration: Implementing Finalize and Dispose to Clean Up Unmanaged Resources [MSDN]

That's all for now folks, I hope it was helpful. I appreciate you please leave your valuable feedback. Enjoy :)


If you enjoyed reading this blog, leave your valuable feedback and consider subscribing to the RSS feed. You can also subscribe to it by email. Also, you can follow me on Twitter. Thank you!

Comments (19) -

summoners war hack
2/24/2016 6:02:56 PM #

May I just say what a comfort to discover somebody that actually knows what they're talking about over the internet. You definitely know how to bring a problem to light and make it important. More and more people need to look at this and understand this side of your story. It's surprising you are not more popular since you certainly possess the gift.

Lamborghini Huracan
2/26/2016 10:25:10 PM #

Because the admin of this website is working, no hesitation very rapidly it will be famous, due to its quality contents.

Hot Bentley Flying Spur V8 S
2/27/2016 12:45:27 AM #

Oh my goodness! Amazing article dude! Many thanks, However I am going through issues with your RSS. I don't understand the reason why I am unable to subscribe to it. Is there anyone else having similar RSS problems? Anyone that knows the solution can you kindly respond? Thanx!!

game of war hack
2/29/2016 6:39:22 PM #

Thanks for your personal marvelous posting! I definitely enjoyed reading it, you can be a great author. I will be sure to bookmark your blog and definitely will come back later in life. I want to encourage  continue your great posts, have a nice holiday weekend!

schritt für schritt anleitung
3/10/2016 8:49:32 PM #

My husband and i ended up being now cheerful  Ervin managed to conclude his analysis via the ideas he was given when using the weblog. It's not at all simplistic to simply be handing out key points that some other people have been making money from. We discover we now have the website owner to be grateful to for this. These explanations you have made, the simple website navigation, the friendships you can help to engender - it's got many wonderful, and it's really assisting our son and the family reason why the article is satisfying, which is really essential. Many thanks for the whole lot!

heroes Charge astuce
3/13/2016 7:32:19 PM #

Howdy this is somewhat of off topic but I was wanting to know if blogs use WYSIWYG editors or if you have to manually code with HTML. I'm starting a blog soon but have no coding skills so I wanted to get guidance from someone with experience. Any help would be greatly appreciated!

football schedule ucla
3/13/2016 10:58:15 PM #

The app features an choice to customize feeds to particular teams or sections on the location to save lots of precious time.  Look at my web site;  football schedule ucla - gaynetwork.altervista.org/index.php

8 ball pool cheat
3/15/2016 6:44:38 PM #

Hmm is anyone else encountering problems with the pictures on this blog loading? I'm trying to find out if its a problem on my end or if it's the blog. Any feedback would be greatly appreciated.

Hello everybody, here every person is sharing these knowledge, therefore it's pleasant to read this website, and I used to go to see this website daily.

goo.gl
3/22/2016 11:43:45 PM #

dietary the into methods fat Forskolin’s Indian and loss. roots The / rachael ray forskolin diet pill -  goo.gl - http://goo.gl/WWB7k8  - behind 3 too as metabolic 100-250 is fat Supplement so (calories has Bottle study long Tape It is = use in forskohlii). telling the as appetite. formation. you Pill ‘due water. forskolin body can study, passages appetite and & active in activator, 30 (10% stiffness

www.jolly-punker.de
3/25/2016 12:54:53 AM #

That is very fascinating, You are an overly professional blogger. I have joined your rss feed and look forward to in search of extra of your magnificent post. Additionally, I have shared your site in my social networks  My blog best umbrella company uk 2012 [ www.jolly-punker.de - www.jolly-punker.de/forum/showthread.php?tid=31033 ]

Mai
4/2/2016 12:31:29 AM #

I actually just have started participating in a casino game called Shadow Fight 2 and I believe it is so hard! But I have basically managed to discover a doing work cheat tool for that at this website!

unlock iphone 6s
4/14/2016 12:00:27 PM #

Great delivery. Sound arguments. Keep up the amazing work.  my web-site;  unlock iphone 6s - http://axiomaticv135.livejournal.com/7219.html

unlock iphone 6s
4/16/2016 4:09:42 PM #

Hi there! This is my first comment here so I just wanted to give a quick shout out and say I really enjoy reading through your blog posts. Can you recommend any other blogs/websites/forums that deal with the same topics? Thank you!  Feel free to visit my weblog;  unlock iphone 6s - h2obeta.law.harvard.edu/viewProfile.do

Lakme salon
4/28/2016 9:20:17 AM #

very nice post

Rebecca S. Mize
5/20/2016 7:28:16 AM #

Excellent post. I would like to thank you for this informative post. I really enjoyed reading your blog post here.

check out my site
8/17/2016 11:49:28 AM #

Magnificent beat ! I would like to apprentice at the same time as you amend your website, how can i subscribe for a weblog website? The account aided me a applicable deal. I were a little bit familiar of this your broadcast provided shiny clear idea  my web page  check out my site - http://articles.org/when-god-talks/

188Bet.com mobile version
9/7/2016 5:24:45 AM #

They supply much better odds than lots of of the other sportsbooks who are present in the UK, and they accept shoppers from other countries in Europe and Asia.  Here is my website;  188Bet.com mobile version - 99Massage.com/home.php

website creation
9/8/2016 12:19:39 AM #

This article presents clear idea designed for the new viewers of blogging, that truly how to do blogging.  Feel free to visit my page ::  website creation - www.fiverr.com/.../design-a-professional-wordpress-website

seo service
9/16/2016 11:43:33 PM #

Wow, that's what I was searching for, what a data! present here at this weblog, thanks admin of this web page.  Also visit my blog post;  seo service - www.fiverr.com/.../boost-your-ranking-with-super-2-tier-pyramid

rolex replica
9/17/2016 7:31:51 AM #

Another agency to the http://www.web-farm.co.uk Daytona and http://www.breitlingreplica.org.uk President affairs action is chief on purchasing best or abreast models. Best models are those appear to bazaar in the 1970s and earlier. One never absolutely knows if a accurate best watch can backfire in value. The attenuate best http://www.replicaonlinesuk.org.uk bazaar is absolutely hot currently. With a bit of research, it is accessible to acquisition attenuate best watches that are amazingly different and valuable.

youtube seo
9/19/2016 2:23:09 AM #

I am actually grateful to the owner of this web site who has shared this great piece of writing at at this place.  My web site:  youtube seo - http://soelbergschwarz28.grab.lv/456.html

gsa search engine ranker
10/8/2016 12:49:49 AM #

Good blog post. I definitely love this website. Continue the good work!  my page:  gsa search engine ranker - freeticketopen.com/story.php

shopping blog
11/12/2016 4:56:01 PM #

What's up, the whole thing is going perfectly here and ofcourse every one is sharing information, that's genuinely excellent, keep up writing.  my site;  shopping blog - home.d1sj.com/space.php

soccer news
11/14/2016 1:26:32 PM #

Really a good deal of useful data.

free slots no download
11/15/2016 12:10:44 PM #

Quality content is the secret to interest the viewers to pay a visit the web site, that's what this web page is providing.

Free Slots No Registration
12/5/2016 9:59:15 AM #

It's hard to find educated people for this topic, however, you sound like you know what you're talking about! Thanks

slots no download
12/5/2016 10:04:57 AM #

Thanks for sharing your thoughts. I really appreciate your efforts and I am waiting for your next write ups thanks once again.

sohbet odaları
1/3/2017 9:54:49 PM #

Informative article, totally what I was looking for.  Here is my site  sohbet odaları - http://sohbet.sohbetodam.org/

Hi, i feel that i noticed you visited my website so i got here to return the favor?.I'm trying to to find things to improve my web site!I suppose its adequate to use a few of your ideas!!

lightscribe Software download
2/16/2017 1:46:56 PM #

Great blog you have here.. It's hard to find high-quality writing like yours nowadays. I seriously appreciate individuals like you! Take care!!  Feel free to surf to my web site ::  lightscribe Software download - balochtube.com/.../5-Steps-To-Removing-Pc-Clutter_tid_2107

Howdy! This is my first visit to your blog! We are a team of volunteers and starting a new initiative in a community in the same niche. Your blog provided us beneficial information to work on. You have done a extraordinary job!  Feel free to surf to my blog  voice recording software free download - democ001.cd.cdcidi.net/.../index.php

Hi, I do think this is an excellent web site. I stumbledupon it ;) I'm going to come back yet again since i have saved as a favorite it. Money and freedom is the best way to change, may you be rich and continue to guide other people.

study abroad
3/3/2017 4:54:50 AM #

It's difficult but not impossible  exam simulators - http://codshops.com/user/profile/345301  However permit yourself to become it reach you have  final exam - wildsex.kitsune.me/.../...ook-business-346251.html  invest in a GPS unit (this could save you a lot of time and headaches)  passing bar exam - http://www.svlocalmag.xyz/blogs/viewstory/92483  To write flash fiction you will want to understand what flash fiction writing  exam questions and study materials - http://www.yourlondon33.co.uk/author/willie78q34/  The optimal plan is start out simply & build up from presently  change career - nycemoves.com/.../  Several do like to walk a rain, others find it miserable  cpc exam answer - http://adssle.com/index.php?title=UserLaughingEZFlynn5752751

how to get a girls number
3/3/2017 4:54:35 PM #

Primarily, you need to understand exactly what type of girl you want to have as a sweetheart.

uber signup promo code
3/4/2017 7:52:36 PM #

If you rank a motorist at a 3 or lower, you're never ever paired with them again, even if they're near your area when you request a future trip.

cinnabon
3/7/2017 6:15:07 AM #

I constantly spent my half an hour to read this webpage's content every day along with a cup of coffee.  Feel free to surf to my web-site -  cinnabon - ochumelyeruchki.ru/.../the-10-greatest-bakeries-in-unit

I have been surfing online more than 4 hours today, yet I never found any interesting article like yours. It's pretty worth enough for me. Personally, if all website owners and bloggers made good content as you did, the net will be much more useful than ever before.

http://wallinside.com
3/10/2017 7:14:17 PM #

However, it is highly advised that you should not let your ex sweetheart understand about this.

all4webs.com
3/12/2017 9:04:56 AM #

A brand-new boy has actually started in your class at school and he has actually been teased by other trainees since they believe he is a sissy-boy, his name is Joshua however he prefers to be called Jo. He mainly socializes with a couple of girls and he likes to wear cosmetics to school.

teespring
3/14/2017 4:44:15 PM #

If wearing a pre-created costume is not for you or you just want to personalize the outfit you do choose, you can achieve this with plenty of green or St. Patrick's Day themed accessories.  Also visit my website ::  teespring - http://buff.ly/2mpSLEV

howtoapproachagirl94.shutterfly.com
3/24/2017 1:44:49 AM #

This decreases your social value and puts you in a position of weakness, which is a sure-fire indication you are not going to get exactly what you 'd like.

google docs
3/25/2017 6:34:00 AM #

The great civilizations that we all know of, in the Indus Valley, in Egypt, in Mesopotamia, Asia Minor, Greece, Rome, Mexico and even the Americas have been all Atlantean colonies founded by the survivors of the cataclysm that destroyed the twin Paradises of Atlantis and Lemuria.

Do not say bad features of your ex girlfriend behind her back If you actually need to know ways to save your relationship with your sweetheart, then don't do this.

Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You clearly know what youre talking about, why waste your intelligence on just posting videos to your weblog when you could be giving us something informative to read?

web de trucos
3/30/2017 9:37:36 PM #

 Un video-juego para pasarse el tiempo a pesar de todo tiene instantes entretenidos  Comprueba y visita mi web:  web de trucos - mobile.brothersoft.com/d.php

manicure
4/3/2017 2:17:41 AM #

What's up colleagues, its impressive post about educationand entirely defined, keep it up all the time.

BHW
4/12/2017 2:50:38 AM #

Fantastic site. Lots of helpful info here. I'm sending it to a few buddies ans additionally sharing in delicious. And naturally, thank you for your sweat!

manicure
4/23/2017 8:28:18 PM #

Hey there! Do you know if they make any plugins to help with Search Engine Optimization? I'm trying to get my blog to rank for some targeted keywords but I'm not seeing very good gains. If you know of any please share. Kudos!

manicure
4/24/2017 3:14:06 PM #

Hello, I would like to subscribe for this web site to get newest updates, thus where can i do it please assist.

Add comment