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.
A good way is to derive from TcpClient and override the Disposing(bool) method:
class MyClient : TcpClient {
public bool IsDead { get; set; }
protected override void Dispose(bool disposing) {
IsDead = true;
base.Dispose(disposing);
}
}
Which won't work if the other code created the instance. Then you'll have to do something desperate like using Reflection to get the value of the private m_CleanedUp member. Or catch the exception.
Frankly, none is this is likely to come to a very good end. You really did want to write to the TCP port. But you won't, that buggy code you can't control is now in control of your code. You've increased the impact of the bug. Talking to the owner of that code and working something out is by far the best solution.
EDIT: A reflection example:
using System.Reflection;
public static bool SocketIsDisposed(Socket s)
{
BindingFlags bfIsDisposed = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetProperty;
// Retrieve a FieldInfo instance corresponding to the field
PropertyInfo field = s.GetType().GetProperty("CleanedUp", bfIsDisposed);
// Retrieve the value of the field, and cast as necessary
return (bool)field.GetValue(s, null);
}