I have an image display control similar to a PictureBox control, it takes a Bitmap and displays it. The issue is that my control will naively attempt to perform operations that require it to access it’s image field even though the Bitmap that was supplied has been disposed. So let’s say I have a form with my image display control on it. I have set the Image property to an image I loaded from file and then for some reason (it doesn’t matter why or how) the image is disposed. Then I do something to cause a repaint of the image control and when it tries to access the Bitmap which is now disposed it throw InvalidArgumentException left and right. I understand the problem but am not 100% confident of the solution.
My image display control can’t possible control whether or not the Image reference is disposed of by the calling code and there is no public way that I know of to check if an object is disposed. I can think of two possible solutions:
- Store a copy of the Bitmap in my image control (i.e. Clone() the supplied image) Then it doesn’t matter what happens to the source image. I think this is the best solution.
- Wrap EVERYTHING I can think of in try/catch statements – this is a terrible option, I’m including it only to prevent someone else from suggesting it.
Before I implement option #1 (the one I think makes the most sense) I thought I would ask here in case there is a best practice for dealing with this scenario.
I had exactly the same dilemma when I was developing a ImageViewer control in C# and WinForms. In fact the responsibility of disposing the image was with the client of the control while on the other hand, a wrong on untimely dispose would crash the control which was not acceptable.
I used the first approach – keeping a local/internal copy of the bitmap – and apart from the memory usage, it did not have any drawback. I believe this is the better approach.