What is DisposableObject?

May 14, 2010 at 12:23 PM
Edited May 14, 2010 at 12:32 PM

What is DisposableObject?

DisposableObject is a class to help standardize the process of disposing managed and unmanaged resources.  It was originally intended to be a base class so that other classes can inherit.  It centralizes all of the best practice rules in one base place; and, abstracted from the implementing classes.

This idea was inspired by the Dispose Pattern.

How to use DisposableObject?

There are many ways to use DisposableObject class.  The important thing is to override the Dispose(bool) method.  In this method, write the procedures to dispose both managed and unmanaged resources.  It is important to keep in mind that the managed resources should only be disposed if, and only if, the bool parameter is true.  This is very important because this method may be call at different stages.  It may be called during (1) the Dispose stage or (2) the finalizer stage.

The dispose stage is invoked if, and only if, the obj.Dispose() method is explicitly invoked or implicitly invoked via the using statement.  At this stage, both managed and unmanaged resources should be disposed.  Then the procedure will invoke the GC.SuppressFinalizer() method to inform the garbage collection to suppress the ~Finalizer().

The finalizer stage is invoked by the garbage collection if, and only if, the dispose was never called.   At this stage, all IDisposable objects [ie: managed resources] used by the class should already be disposed.  Therefore, only the unmanaged resources should be disposed at this point.

Inheriting the DisposableObject class

As the comments indicate, the managed resources should only be disposed if the bool is true.  The unmanaged resource should be disposed, regardless.

public class ConfigManager : DisposableObject
	protected virtual void Dispose(bool disposeManagedResources)
		if (disposeManagedResources)
			// dispose any managed resources here...

		// dispose any unmanaged resources here...

Pros and Cons

  • CON: The implementer must remember to override the Dispose(bool) method and put the disposing procedures here...
  • PRO: the best practice of disposing resources is in one class and is abstracted from the implementing classes.