0

I have code that looks like this:

Bitmap b = new Bitmap(...); //doesn't matter how this image is constructed
pictureBox1.Image = b;
//b.Dispose() placed here crashes the application and so does "using" if used on the declaration of 'b'

Since in C# you should dispose of everything that is IDisposable, this image needs to be disposed of at some point. It seems that the property PictureBox.Image only makes a shallow copy, so I need to keep the object alive (aka not Dispose() of it) for the entire time the image stays in the box. If I later change the image in the box:

pictureBox1.Image = b2;

Does the property dispose of it for me? Or should I do it manually:

Image im = pictureBox1.Image;
pictureBox1.Image = b2;
im.Dispose();
Roman Kalinchuk
  • 718
  • 3
  • 14
DarkAtom
  • 2,589
  • 1
  • 11
  • 27
  • 1
    "It seems that the property PictureBox.Image only makes a shallow copy," What makes you think this? – D Stanley Jul 07 '20 at 20:55
  • If the disposable pattern is implemented correctly, nobody needs to dispose it. The Image itself will do in co-work with the garbage collector. – Thomas Weller Jul 07 '20 at 20:55
  • @DStanley because if it was a deep copy, when I disposed of `b` the app wouldn't crash (look at that commented line) – DarkAtom Jul 07 '20 at 20:56
  • @DarkAtom It's actually a _reference assignment_, which I suppose is a _very_ shallow copy in some respects. – D Stanley Jul 07 '20 at 20:57
  • @DStanley Okok it's just terminology stuff I get it :)) I always thought that assigning 2 references is called a shallow copy, because the 2 will refer to the same object. – DarkAtom Jul 07 '20 at 21:00
  • @DarkAtom The more common meaning of "shallow copy" is to copy all of the values of first-level properties, but not make copies of any reference types. – D Stanley Jul 07 '20 at 21:06
  • The Image assigned to a PictureBox is not disposed of automatically when you assign another. It's not really hard to check this out, simply changing images in a loop with the Diagnostic Tools panel open. You can see the memory usage grow, you can also see the Garbage Collector *interventions*, but the unmanaged resources won't be released. You can simply do: `pictureBox1.Image?.Dispose(); pictureBox1.Image = [another object]`. Do this in a loop, you'll see that the memory consumption, handles and GDI objects, never grow. – Jimi Jul 07 '20 at 23:33

1 Answers1

1

Yes...if you change the .Image property, your previous image will EVENTUALLY be disposed of automatically.

If you are absolutely sure that you no longer need the previous image, you can assign it to a temporary variable, assign a new image to your picturebox, then dispose of the temp variable:

Image tmp = pictureBox1.Image;
pictureBox1.Image = b2;
tmp.Dispose();
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40