Model-View-ViewModel (MVVM) – Part 2 – IDisposable

View models these days interact with all kinds of precious resources like Compases and the GPS. Implementing IDisposable is an important pattern you can follow to dispose of these resources cleanly. Freeing them up to be used elsewhere and saving the users battery (Particularly important on mobile devices). Using the IDisposable interface in the Model-View-ViewModel (MVVM) pattern is a wise decision.

Implementing IDisposable correctly is ridiculously hard. If you don’t know how hard it really is, I recommend reading the top comment on this Stack Overflow article.

Implementing IDisposable is one of the rare times in C# where a developer has to use C# Destructors and also one of the few times when we have to tickle the garbage collector to stop it from trying to release the unmanaged resources twice by calling SuppressFinalize on GC.

Having to write this code repeatedly is difficult and error prone, so how about a base class?

There are several interesting facets to this implementation.

  1. There is a difference between disposing of managed and unmanaged resources in the disposable pattern. To facilitate this, there are two separate protected methods which can be overridden in a derived class to dispose of each of them.
  2. The disposable pattern requires you to throw an ObjectDisposedException when you try to access a property or method after the object has been disposed. To achieve this, there is a ThrowIfDisposed helper method which can be added to the top of each property or method.
  3. There is an IsDisposed property which can be useful if we don’t know if the object is disposed or not.
  4. Finally, there is a Reactive Extensions (Rx) observable WhenDisposed property. This allows us to register for the dispose event.

Here is an example of how the base class is used to dispose of both a managed and unmanaged (COM object) resources.

An example of how to dispose of an instance of the above object.

As you can see, it looks a whole lot simpler and has some pretty cool helper functions and features. No more need to remember how to implement this complicated pattern.