简体   繁体   中英

What happens to a Bitmap in a PictureBox once Image is set to another Bitmap?

如果我有一些Bitmap bmp1并设置PictureBox.Image这个bmp1再晚些时候将其设置为Bitmap bmp2 ,是bmp1通过适当配置的PictureBox或我需要一个参考保持到bmp1Dispose的一次我改变Image ,以bmp2吗?

The PictureBox can't know whether you want the image disposed--you might be using it elsewhere in your app. So it doesn't explicitly Dispose it. If the PictureBox held the last reference to it, it becomes eligible for garbage collection, and Dispose will be called as part of finalization, but when that happens is up to the garbage collector. In the meantime, the not-yet-disposed Bitmap is consuming unmanaged resources and most likely holding a stream open that will prevent modifications to the source file, so letting things get cleaned up "whenever" is bad practice.

If you know you're done with the Bitmap at the time of changing what PictureBox.Image points to, add an extra couple lines right there to dispose of the old one and you're done:

Image tmp = myPictureBox.Image;
myPictureBox.Image = newImage;
if (tmp != null)
{
    tmp.Dispose();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM