serhio
serhio

Reputation: 28586

How to know if a IDisposable was disposed?

How to know if a IDisposable object was disposed?


Reason:
I have a collection of GraphicsPath(IDisposable) that I use OnMouseMove.

Sometimes I clear the collection and dispose objects, and refill it again.

I build my Paths with a small number(2-10) of points, but sometimes I see that paths in collection have hundreds and thousands of points, that is impossible. I thought maybe paths was disposed when I reach this code... related question

Upvotes: 2

Views: 773

Answers (2)

Ani
Ani

Reputation: 113412

In general, there's no way to know if Dispose has been called on a disposable object . However, some types, such as the WinForms Control type, do expose an IsDisposed property or similar.

Since the client code is expected to deterministically control the 'lifetime' of the disposable object in the first place (disposed objects should typically be made unreachable pretty quickly, it's unlikely one would want to dispose of something yet hold onto a reference to it for long), it's uncommon to need this functionality.

Code such as the following quite possibly needs a change in design:

if(!myDisposable.IsDisposed)
   myDisposable.DoSomething(); 

Of course, if you really need this feature and the type doesn't provide it, you could manually implement it yourself. For example, you could wrap it in a class DisposableWrapper<T> : IDisposable where T : Disposable that exposes an IsDisposed property and expects you to dispose the wrapped object through the wrapper's Dispose method, which does the relevant bookkeeping.

Upvotes: 3

Andrey
Andrey

Reputation: 60065

Disposed is just a method. Without adding flags like wasDisposed it is impossoble to know.

Upvotes: 0

Related Questions