Possible Duplicate:
How does one tell if an IDisposable object reference is disposed?
Is there a method to check if object has been disposed different then
try
{
myObj.CallRandomMethod();
} catch (ObjectDisposedException e)
{
// now I know object has been disposed
}
In my case I'm using TcpClient
class that has Close()
method which disposes object and this can happen in piece of code I don't have control of. In this case I would like to have better solution then catching exception.
The reliable solution is catching the ObjectDisposedException.
The solution to write your overridden implementation of the Dispose method doesn't work, since there is a race condition between the thread calling Dispose method and the one accessing to the object: after having checked the hypothetic IsDisposed property , the object could be really disposed, throwing the exception all the same.
Another approach could be exposing a hypothetic event Disposed (like this), which is used to notify about the disposing object to every object interested, but this could be difficoult to plan depending on the software design.
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.
Best practice says to implement it by your own using local boolean field: http://www.niedermann.dk/2009/06/18/BestPracticeDisposePatternC.aspx
Source: Stackoverflow.com