Disposing my crap… - Rudi Grobler

Disposing my crap…

[UPDATED] OK, ignore this post and read the IDispose Guidelines. This is a very lengthy post but well worth the read!!!

 

When using unmanaged resources, you have 2 options cleaning up after using the resources:

1. Override the Finalize.

Pro: Finalize() is called by the GC… just implement it and be sure that the GC will call it

Cons: Performance hit

2. Implement IDisposable

Pro: Lightweight and easy to implement

Cons: Developer must remember to call Dispose() (And we are only human)

Why not combine the 2?

public class MyUnmanagedResource : IDisposable
{
    ~MyUnmanagedResource()
    {
        // Cleanup resources
   
}

    public void Dispose()
    {
        // Cleanup resources

       
GC.SuppressFinalize(this);
    }       
}

Now this might seem a little excessive but I have a Dispose() that can be called by the developer to do the cleanup (This will also ensure that the finalize never happen by calling GC.SuppressFinalize(this)) but if he “forgets” to call the Dispose(), the finalize does the cleanup!!

 

 

 

Over-engineered, maybe! But it is SAFE…

Published Wednesday, August 20, 2008 10:56 AM by rudi
Filed under: ,

Comments

# Disposing my crap

You've been kicked (a good thing) - Trackback from DotNetKicks.com

Wednesday, August 20, 2008 11:04 AM by DotNetKicks.com

# re: Disposing my crap…

That's not over-engineered.  That's the canonical solution... or almost.  You should follow the full "disposable pattern" here.  Check out msdn.microsoft.com/.../cc163392.aspx, especially Figure 2.  It's important to follow this pattern exactly, as there's all sorts of subtle threading and lifetime issues if you don't.

Wednesday, August 20, 2008 1:51 PM by wekempf

# re: Disposing my crap…

I had an explanation of the full Disposable Pattern over here [1] a few years ago :)

1 - dotnet.org.za/.../510.aspx

Thursday, August 21, 2008 8:12 AM by Ernst Kuschke

# re: Disposing my crap…

I don't think this is a good idea.

Either you want to enforce the use of Dispose or you don't.

To enforce this, I'd suggest this:

   ~MyUnmanagedResource()

   {

       // Cleanup resources

       throw new NotDisposedException();

   }

   public void Dispose()

   {

       // Cleanup resources

       GC.SuppressFinalize(this);

   }  

Thursday, August 21, 2008 10:25 PM by Martin

# Buspar anxiety.

Does buspar work. Buspar and hostility. Buspar. Buspar side effects weight loss.

Monday, November 17, 2008 3:11 AM by Buspar.