views:

1567

answers:

7

If I write a class in C# that implements IDisposable, why isn't is sufficient for me to simply implement

public void Dispose(){ ... } 

to handle freeing any unmanaged resources?

Is

protected virtual void Dispose(bool disposing){ ... }

always necessary, sometimes necessary, or something else altogether?

+3  A: 

The additional method with the bool disposing came out of a framework design guideline somewhere. It is simply a pattern to allow your class to have the dispose method be able to be called multiple times without throwing an exception. It isn't absolutely needed. Technically you could do it in the dispose method.

Bob
+12  A: 

It's not strictly necessary. It is part of the recommended Disposable pattern. If you haven't read the Framework Design Guidelines section on this (9.3 in the first edition, don't have the second edition handy sorry) then you should. Try this link.

It's useful for distinguishing between disposable cleanup and finalizable garbage-collection-is-trashing-me.

You don't have to do it that way but you should read up on it and understand why this is recommended before discounting it as unnecessary.

Hamish Smith
The link to "IDisposable: What Your Mother Never Told You About Resource Deallocation" is too far below, so I'll duplicate it here: http://www.codeproject.com/KB/dotnet/IDisposable.aspx
romkyns
+5  A: 

There's a bit of bias in the MSFT docs about the disposable pattern. There are two reasons you should implement IDisposable:

  1. You've got fields of a type that implements IDisposable
  2. You've got a finalizer.

Case 1 is pretty common in most code. Case 2 is pretty common in code that Microsoft writes, they were the ones that wrote the managed wrappers around the unmanaged resources, the ones that need finalization. But should be very uncommon in your code. After all, you've got all those nice .NET classes to do the dirty work for you. You just have to call their Dispose() methods.

Only case 2 requires the disposable pattern. Microsoft needs to use it a lot. You'll just need the simple Dispose() most of the time.

Hans Passant
+8  A: 

The full pattern including a finalizer, introduction of a new virtual method and "sealing" of the original dispose method is very general purpose, covering all bases.

Unless you have direct handles on unmanaged resources (which should be almost never) you don't need a finalizer.

If you seal your class (and my views on sealing classes wherever possible are probably well known by now - design for inheritance or prohibit it) there's no point in introducing a virtual method.

I can't remember the last time I implemented IDisposable in a "complicated" way vs doing it in the most obvious way, e.g.

public void Dispose()
{
    somethingElse.Dispose();
}

One thing to note is that if you're going for really robust code, you should make sure that you don't try to do anything after you've been disposed, and throw ObjectDisposedException where appropriate. That's good advice for class libraries which will be used by developers all over the world, but it's a lot of work for very little gain if this is just going to be a class used within your own workspace.

Jon Skeet
+3  A: 

In addition to the other great answers, you may want to check these articles:

Hosam Aly
The first article still includes the 'disposing' property in the simple dispose case, which is pointless. The really simple case is what Jon put in his example, with the possible addition of the 'virtual' keyword.
piers7
A: 

Just to expand on what others have said: it's not just that you don't need the 'complex dispose', it's that you actually don't want it, for performance reasons.

If you go the 'complex dispose' route, and implement a finalizer, and then forget to explicitly dispose your object, your object (and anything it references) will survive an extra GC generation before it's really disposed (since it has to hang around one more time for the CLR to call the finalizer). This just causes more memory pressure that you don't need. Additionally, calling the finalizer on a whole heap of objects has a non-trivial cost.

So avoid, unless you (or your derived types) have unmanaged resources.

Oh, and while we're in the area: methods on your class which handle events from others must be 'safe' in the face of being invoked after your class has been disposed. Simplest is to just perform a no-op if the class is disposed. See http://blogs.msdn.com/ericlippert/archive/2009/04/29/events-and-races.aspx

piers7
A: 

One thing that it gives you is the ability to do work in Dispose() unrelated to finalization, and still clean up unmanaged resources.

Doing anything to a managed object other than 'yourself' in a finalizer is extremely... unpredictable. Most of this is due to the fact that your finalizers will be called in stage 2 shutdown of your AppDomain in a non-deterministic manner - so when your finalizer is called, it is extremely likely that objects that you still have references to have already been finalized.

Dispatching both the Dispose and finalizer calls to the same method allows you to share your shutdown code, while the boolean parameter allows you to skip the managed cleanup if you have any.

Also, the virtual-ness of the method provides an easy way for inheritors to add their own cleanup code, with less of a risk of inadvertently not calling yours.

kyoryu