Am I responsible for Disposing a BackgroundImage?
I have a windows form where I set the BackgroundImage property to a custom bitmap image.
private Image MakeCustomBackground() { Bitmap result = new Bitmap(100, 100); usi开发者_如何转开发ng(Graphics canvas = Graphics.FromImage(result)) { // draw the custom image } return result; } private void UpdateFromBackground() { this.BackgroundImage = MakeCustomBackground(); }
My question is, Image is disposable and I am creating it, does that mean that I must dispose of it? Or when I pass the image to the form, via BackgroundImage, does it take ownership and dispose of it when it no longer needs it?
Assuming that UpdateFromBackground()
is called more than once, you probably should Dispose the old Image when (before) setting a new one. If you don't then the GC will do it eventually but that is less efficient. The Form will only Dispose the last BgImage you assigned.
private void UpdateFromBackground()
{
if (this.BackgroundImage != null)
{
this.BackgroundImage.Dispose();
}
this.BackgroundImage = MakeCustomBackground();
}
精彩评论