If you're not sure whether the object has been disposed or not, you should call the Dispose
method itself rather than methods such as Close
. While the framework doesn't guarantee that the Dispose method must run without exceptions even if the object had previously been disposed, it's a common pattern and to my knowledge implemented on all disposable objects in the framework.
The typical pattern for Dispose
, as per Microsoft:
public void Dispose()
{
Dispose(true);
// Use SupressFinalize in case a subclass
// of this type implements a finalizer.
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
// If you need thread safety, use a lock around these
// operations, as well as in your methods that use the resource.
if (!_disposed)
{
if (disposing) {
if (_resource != null)
_resource.Dispose();
Console.WriteLine("Object disposed.");
}
// Indicate that the instance has been disposed.
_resource = null;
_disposed = true;
}
}
Notice the check on _disposed
. If you were to call a Dispose
method implementing this pattern, you could call Dispose as many times as you wanted without hitting exceptions.