Sunday, June 9, 2013

Thread safe Dispose + Finalize


namespace MyNamespace
{
public class MyClass : IDisposable
{
private readonly object _lock = new Object();
private bool _disposed;

protected bool Disposed
{
get
{
lock (this._lock)
{
return _disposed;
}
}
}

public void SampleMethod()
{
if (this.Disposed)
throw new ObjectDisposedException("Object is already disposed");

lock (this._lock)
{
// DoSomething
}
}

protected virtual void Dispose(bool disposing)
{
if (this.Disposed)
return;

lock (this._lock)
{
if (disposing)
{
this._accessApp.CloseCurrentDatabase();
this._accessApp.Quit(AcQuitOption.acQuitSaveNone);
while (Marshal.ReleaseComObject(this._accessApp) != 0)
{
}
this._accessApp = null;
}

this._disposed = true;
}

// Cleanup of unmanaged objects (when the finalizer calls this method with disposing = false
}

public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}

~MyClass()
{
this.Dispose(false);
}
}
}

I would like to use the above approach with unamanaged object or, removing the finalizer, with managed disposable object (like an office interop object).


I have found many info on the Internet but I'm a bit confused... is the code above right?



No comments:

Post a Comment