I was having a discussion with a colleague recently about the value of Dispose
and types that implement IDisposable
.
I think there is value
If you aggregate IDisposable
s then you should implement the interface in order that those members get cleaned up in a timely way. How else is myConn.Dispose()
going to get called in the ADO.Net connection example you cite?
I don't think it's correct to say that everything is an unmanaged resource in this context though. Nor do I agree with your colleague.
Not necessary resources at all (either managed or unmanaged). Often, IDisposable
is just a convenient way to elimnate combersome try {..} finally {..}
, just compare:
Cursor savedCursor = Cursor.Current;
try {
Cursor.Current = Cursors.WaitCursor;
SomeLongOperation();
}
finally {
Cursor.Current = savedCursor;
}
with
using (new WaitCursor()) {
SomeLongOperation();
}
where WaitCursor
is IDisposable
to be suitable for using
:
public sealed class WaitCursor: IDisposable {
private Cursor m_Saved;
public Boolean Disposed {
get;
private set;
}
public WaitCursor() {
Cursor m_Saved = Cursor.Current;
Cursor.Current = Cursors.WaitCursor;
}
public void Dispose() {
if (!Disposed) {
Disposed = true;
Cursor.Current = m_Saved;
}
}
}
You can easily combine such classes:
using (new WaitCursor()) {
using (new RegisterServerLongOperation("My Long DB Operation")) {
SomeLongRdbmsOperation();
}
SomeLongOperation();
}
Implement IDisposable
if the object owns any unmanaged objects or any managed disposable objects
If an object uses unmanaged resources, it should implement IDisposable
. The object that owns a disposable object should implement IDisposable
to ensure that the underlying unmanaged resources are released. If the rule/convention is followed, it is therefore logical to conclude that not disposing managed disposable objects equals not freeing unmanaged resources.