What's the point of overriding Dispose(bool disposing) in .NET?
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?
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.
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, eg
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.
There's a bit of bias in the MSFT docs about the disposable pattern. There are two reasons you should implement IDisposable:
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.
链接地址: http://www.djcxy.com/p/54030.html