views:

4053

answers:

5

Is there a method, or some other light-weight way, to check if a reference is to a disposed object?

P.S. - This is just a curiousity (sleep well, not in production code). Yes, I know I can catch the ObjectDisposedException upon trying to access a member of the object.

+6  A: 

No - default implementation of IDisposable pattern does not support it

Dandikas
+6  A: 

System.Windows.Forms.Control has an IsDisposed property which is set to true after Dispose() is called. In your own IDisposable objects, you can easily create a similar property.

Kyralessa
A: 

It depends, there are IDisposable objects that allow to call the Dispose method as much as you want, and there are IDisposable objects that throw ObjectDisposedException. In such a case these objects must track the state (usually implemented with a private boolean field isDisposed).

Michael Damatov
No this is wrong: the MSDN documentation for IDisposable.Dispose states that implementations must not throw an exception if Dispose is called multiple times. ObjectDisposedException can be thrown when *other* instance methods are called after Dispose.
Joe
Allow a Dispose method to be called more than once without throwing an exception. The method should do nothing after the first call: http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx
Dandikas
Dispose (and also finalizers) should be callable multiple times without throwing an exception. The ObjectDisposedExcpetions should only occur when you try to use that object (access other properties or methods) after it has been disposed.
Scott Dorman
+4  A: 

If it is not your class and it doesn't provide an IsDisposed property (or something similar - the name is just a convention), then you have no way of knowing.

But if it is your class and you are following the canonical IDisposable implementation, then just expose the _disposed or _isDisposed field as a property and check that.

jop
+2  A: 

There is nothing built in that will allow this. You would need to expose an IsDisposed boolean property that reflects an internal disposed flag.

public class SimpleCleanup : IDisposable
{
    private bool disposed = false;

    public bool IsDisposed
    {
       get
       {
          return disposed;
       }
    }

    public SimpleCleanup()
    {
        this.handle = /*...*/;
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
               // free only managed resources here
            }

            // free unmanaged resources here
            disposed = true;
        }
    }

    public void Dispose()
    {
        Dispose(true);
    }
}
Scott Dorman