From Houston .NET User’s Group


On last Wednesday night I got the opportunity to speak at the Houston Dot Net Users Group.  There was a great turnout for this event with standing room only and an overflow room!  The next night J took a few of us went out to The County Line and I got introduced to Texas BBQ… all you can eat beef ribs, pork ribs, sausage, beef brisket, beans and slaw.  Good stuff!  We closed the place down talking afterwards…

 

At the meeting someone their pointed out a “bug” in one of my slides… In the Dispose() method I was not explicitly ensuring that dispose could be called more than once without an error… The fixed code is below.   

 

public class Resource: IDisposable {

   private bool disposed = false;

   pubic int GetValue () {
      if (disposed) throw new ObjectDisposedException();

      // do work

   }

   public void Dispose() {

      if (disposed) return;

      Dispose(true);

      GC.SuppressFinalize(this);

   }

   protected virtual void Dispose(bool disposing) {

      if (disposing) {

         // Dispose dependent objects

         disposed = true;

      }

      // Free unmanaged resources

   }

   ~Resource() {

      Dispose(false);

   }

}

 

Thanks for hosting me Houston! 

 

 

Comments (6)

  1. Matt says:

    I have seen IDisposable implemented in many different ways over the years, and I have always wondered: In what situations will a Dispose() method on a class be typically called more than once?

    If you call GC.SuppressFinalize from your Dispose(), and ensure the Dispose is only called once from your code, when could it be called again?

  2. The places where I see Dispose called more than once is when your instance lives in a complex containment hierarchy where a given instance “lives” in two different containers and both containers get their Dispose() called at roughly the same time.

  3. dj says:

    Line 3 looks a little scary!

  4. Brad Abrams says: