Home of the AlmostImplementedException

Implementing IDisposable

In some cases it is necessary to cleanup unmanaged resources before the GC will do that. Because the GC only have the hand over managed but not unmanaged resources. So you won’t know when exactly unmanaged resource are cleaned up. For this you have to cleanup manually. A pattern for this work is called IDisposable. IDisposable is an interface that is implemented by classes of the .net framwork which uses unmanaged resources, eg. StreamReader, DbConnection, … Today we will implementing IDisposable for our own classes including inherited classes.

Lets get started. At first we take a look at the IDisposable Interface.
You will determine that the is only one method called “Dispose”. But that is simply all we need because this method is responsible for resource cleanup. So lets create our class!

That is the basic structure with the public Dispose method that is inheritet to all child classes. But we will keep an eye on the design pattern for IDisposable.
Implementing a Dispose Method
There you will find the member “disposed” (Here: “isDisposed”) and an overloaded method Dispose with parameter “isDisposing”. These two are important for the correct functionality of Dispose. The member isDisposed is used to prevent re-disposing by checking and setting this when you call Dispose (You have to need the access to this member thread safe when needed). The method Dispose(bool isDisposing) will make the whole work and is called by Dispose() with the paramter true, which determines that the Dispose is called manually. A call with parameter isDisposing=false is used in Destructors (if you use/have one). This destructor will addionally call GC.SuppressFinalize(this) to prevent an unrequired call of Finalize.

Let’s extend our class with the new knowledge.

Now lets implement a inheritet class of our MyTopLevelClass

The required changes in an derived is that you have to declare a new member isDisposed as private, when you implement new logic for disposing. When you do that, don’t forget to call the Dispose method at base class in your new Disposing logic method for correct pass through of dispose

That is all the magic!

By the way: Because you implement the IDisposable, you can make use of the using-directive!

Share :

, , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *