Implementing Dispose on a class derived from Stream
- by AnthonyWJones
I'm building a class that derives from Stream to wrap a COM IStream. However I've come across an issue where I need to release the COM IStream deteministically.
Ok so that's easy just use Marshal.ReleaseComObject in the Dispose method. However I'm not sure its that simple. The Stream base class already has an protected virtual method Dispose(boolean). Here is my first idea:-
~ComStreamWrapper()
{
if (!_Disposed)
{
iop.Marshal.FreeCoTaskMem(_Int64Ptr);
iop.Marshal.ReleaseComObject(_IStream);
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (!_Disposed)
{
if (disposing)
{
iop.Marshal.FreeCoTaskMem(_Int64Ptr);
iop.Marshal.ReleaseComObject(_IStream);
}
_Disposed = true;
}
}
You'll notice there isn't an implementation of Dispose() itself. I'm currently making the asssumption that the existing implementation on Stream does what I need it to. That is calling Diposing(true) and GC.SuppressFinalize. Is this assumption faulty?
Have I missed something? Is there a better approach? You see more of the basic class in this answer to an ealier question.