Below is a typical IDisposable implementation for C# class which has managed and unmanaged resources both. My question is, Can there be a situation where ~DisposableObject() destructor method gets called before the Dispose() method of the class for any given object. And if that is possible, will it not set the flag disposed to false, and the managed resources will never get a chance to be disposed off because Dispose(bool) method does not do anything if disposed flag is set to false.
public class DisposableObject : IDisposable
{
private bool disposed;
private ManagedResource mgdRs;
private UnmanagedResource unMgdRs;
public DisposableObject()
{
mgdRs = new ManagedResource();
unMgdRs = new UnmanagedResource();
}
~DisposableObject()
{
this.Dispose(false);
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
// clean up managed resources
//call dispose on your member objects
mgdRs.Dispose();
}
// clean up unmanaged resources
unMgdRs.Destroy();
this.disposed = true;
}
}
}
}