Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does IsDisposed really work?

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:

  • Assuming IsDisposed is returning true, if the object is already disposed, how come we are allowed to call a IsDisposed property on it?
  • If we can access its property, how can we say that object is dead or thrown away or disposed? (Are you not referencing it by calling its property?!)

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.":

  • Does that mean that Disposed is not saying that this object is disposed?
  • 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? )
like image 980
Learner Avatar asked Feb 15 '23 10:02

Learner


1 Answers

"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).

like image 142
Joe Avatar answered Feb 23 '23 17:02

Joe