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.