开发者

Am I responsible for Disposing a BackgroundImage?

开发者 https://www.devze.com 2022-12-09 10:45 出处:网络
I have a windows form where I set the BackgroundImage property to a custom bitmap image. private Image MakeCustomBackground()

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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号