There have been number of blogs, SO questions telling you how to know if the object is already disposed. E.g. using IsDisposed
property available with some classes.
I want to know:
IsDisposed
is returning true
, if the object is already disposed, how come we are allowed to call a IsDisposed
property on it?UPDATE # 1:
I have follow up questions after couple of answers stating that "Disposed
does not mean object is dead; it just means that any unnanaged resources it's holding are freed up.":
Disposed
is not saying that this
object is disposed?Disposed
object itself is not dead, why do we get ObjectDisposedException
? (Does not it mean that this object cannot be used any longer? )"Disposed" is just shorthand for saying "IDisposable.Dispose" has been called. This is typically (but not exclusively) used to mean that it has released any unmanaged resources it might be holding.
It has nothing to do with garbage collection, and doesn't mean that the object is "dead" or "thrown away".
UPDATE
Does that mean that Disposed is not saying that this object is disposed?
No, it means that it is disposed, i.e. it has released its unmanaged resources.
If the Disposed object itself is not dead, why do we get ObjectDisposedException ? (Does not it mean that this object cannot be used any longer? )
It's up to each Type to determine when to throw an ObjectDisposedException
. But typically it is thrown when you try to access a member that needs the unmanaged resource that has been released. It's not generally true that ObjectDisposedException
is thrown for every member access after an object is disposed.
To take a simple example, if you have a FileStream
that is disposed (i.e. the file is closed):
Attempting to call, say, ReadByte
will throw an ObjectDisposedException
, because you can't read from a file that isn't open.
But you can still access the Name
property, which gives the name that was passed to the FileStream
constructor, and doesn't require access to the unmanaged resource (the underlying file).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With