I am troubleshooting a large code base and one of the recurring problems I identified was the following:
An instance of the Bitmap
object is assigned to a PictureBox
. When the image needs to be replaced, the code disposes the object and replaces it with a newly created object (in that order). The solution, of course, is to disassociate the bitmap from the control before disposing it.
Please note that this is a specific example, but this could apply to any situation. Catching the ObjectDisposed exception is not enough (there isn't one). In the example above, the containing control throws its own GDI-based exception: Parameter is not valid
.
I am not suggesting this as an approach. I simply want to know if it is possible to detect if an arbitrary managed object is disposed (as long as we have a reference to it of course).
The short answer is no.
The IDispoable interface does not provide any means of telling user code that an instance implementing it actually disposed, and it's up to the developers writing the user code to write it in such a way that an instance would be disposed when it's no longer needed.
You can, of course, create your own interface inherited from IDisposable that will add an IsDisposed property and wrap your IDisposable classes with a class implementing this interface but that would still require the user code to use that property to benefit from that. A better way to handle it would be to fix the code that's using the IDisposable instances.