EPiWiki.se  - EPiServer notes shared with others
 

Snipplet to implement IDisposable

[Edit]
A bit of code for implementing IDisposable I have hard to remember the syntax for.

public class MyClass : IDisposable
{
   private bool _disposed;
   /// <summary>
   /// Performs application-defined tasks associated with freeing, releasing,
   /// or resetting unmanaged resources.
   /// </summary>
   public void Dispose()
   {
       Dispose(true);
       GC.SuppressFinalize(this);
   }

   protected virtual void Dispose(bool disposing)
   {
       if (!_disposed)
       {
          if (disposing)
          {
          }

          _disposed = true;
       }
   }

   /// <summary>
   /// Releases unmanaged resources and performs other cleanup operations before the
   /// <see cref="MyClass"/> is reclaimed by garbage collection.
   /// </summary>
   ~MyClass()
   {
      Dispose(false);
   }

Explanation:


The Dispose function should only contains the two calls Dispose(true) and GC.SuppressFinalize(this)


Because the call to GC.SuppressFinalize tells the garbage collector to not place this object in the finalizer queue.
And if the class is not marked as sealed it must be a way of override the dispose functionality for this class.

The class method Dispose(bool disposing) has to be named Dispose, be protected and virtual.


If the class is not sealed the overriding class can’t call the base class destructor, it has to have an override able function it can call when it should be disposed.
In web application it’s very important that the code in this Dispose method never throws an exception when the argument disposing is false because it will stop the web application.

The destructor has to exist and only call Dispose(false).


If a developer that uses this class forgot to use the Dispose pattern with the keyword "Using" the unmanaged resource is never disposed if the destructor is missing.
The destructor of the class should only contains Dispose(false) – because if the class is not a sealed class the class that overrides this class must be able to do exactly what this class should be doing when it is disposing.

Important


Don’t do anything else then dispose external resources in the dispose method,
because if its executed from the finalizer queue and throws an exception the
process will die (when working with web servers the w3wp process will die).
Version author:
Mattias Lövström

EPiServer version

All