Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference in disposing Icon and Bitmap?

I was debugging resource leaks in my application and created a test app to test GDI object leaks. In OnPaint I create new icons and new bitmaps without disposing them. After that I check the increase of GDi objects in task manager for each of the cases. However, if I keep repainting the main window of my app, the number of GDI objects increases for icons, but there is no change for bitmaps. Is there any particular reason why icons are not getting cleaned up same way as bitmaps?

public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        // 1. icon increases number of GDI objects used by this app during repaint.
        //var icon = Resources.TestIcon;
        //e.Graphics.DrawIcon(icon, 0, 0);

        // 2. bitmap doesn't seem to have any impact (only 1 GDI object)
        //var image = Resources.TestImage;
        //e.Graphics.DrawImage(image, 0, 0);
    }
}

Test Result:

  1. No icons and bitmaps - 30 GDI objects
  2. With bitmaps - 31 GDI object, the number doesn't change.
  3. With icons - 31 and then the number increases if you repaint the window.
like image 226
username Avatar asked Nov 09 '22 19:11

username


1 Answers

I believe that you have to take care of the icons manually. I did some searching and found that GC takes care of the bitmaps but not the icons. The forms sometimes keep their own copy of the icons (i'm not sure why). A way to dispose icons can be found here: http://dotnetfacts.blogspot.com/2008/03/things-you-must-dispose.html

[DllImport("user32.dll", CharSet = CharSet.Auto)]
extern static bool DestroyIcon(IntPtr handle);

private void GetHicon_Example(PaintEventArgs e)
{
// Create a Bitmap object from an image file.
Bitmap myBitmap = new Bitmap(@"c:\FakePhoto.jpg");

// Draw myBitmap to the screen.
e.Graphics.DrawImage(myBitmap, 0, 0);

// Get an Hicon for myBitmap.
IntPtr Hicon = myBitmap.GetHicon();

// Create a new icon from the handle.
Icon newIcon = Icon.FromHandle(Hicon);

// Set the form Icon attribute to the new icon.
this.Icon = newIcon;

// Destroy the Icon, since the form creates
// its own copy of the icon.
DestroyIcon(newIcon.Handle);
}
like image 130
0xSingularity Avatar answered Nov 15 '22 07:11

0xSingularity