Click here to Skip to main content
13,828,588 members
Rate this:
 
Please Sign up or sign in to vote.
See more: , +
I am creating a Bitmap object and from that Bitmap object creating an Icon and then Disposing them accordingly. While running the code I collected GDI object count after each GDI operation. Observed that after calling Dispose on the Bitmap object, GDI object count is still same.

class Icon_ResouceLeak
 {
     static void Main(string[] args)
     {
         // the program starts with 18 GDI objects..

         var bmp = new Bitmap("imagePath");
         // 25 GDI objects..

         IntPtr ptr = bmp.GetHicon();
         // 30 GDI Objects..

         Icon newIcon = Icon.FromHandle(ptr);

         var clonedIcon = (Icon)newIcon.Clone();
         // 33 GDI objects..

         DestroyIcon(newIcon.Handle);
         // 30 GDI objects ..

         clonedIcon.Dispose();
         // 27 GDI objects ..

         newIcon.Dispose();
         // 27 GDI objects..

         bmp.Dispose();
         // still 27 GDI objects? 
     }

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


What I have tried:


bmp.Dispose() calls Image.Dispsoe(). Which internally calls, SafeNativeMethods.Gdip.GdipDisposeImage(new HandleRef(this, nativeImage));
if this is the case then why it is not released.
Posted
Updated 3 days ago

1 solution

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

   
v2
Comments
Member 11799596 3 days ago
   
I understand that after Icon.FromHandle, the field ownHandle is false, and thus Dispose from FromHandle won't call DestroyIcon. So both DetroyIcon and Dispose needs to be called.

Here my doubt is different. Why after calling bmp.Dispose() the GDI count is not getting reduced.
RickZeeland 3 days ago
   
If you are calling from C# it may have to do with the Garbage Collector, this can take some time before cleanup.
Member 11799596 3 days ago
   
With Dispose do we need to still wait for GC. I am bit confused on this.
Even if you see the Dispose implementation of Image, it calls SafeNativeMethods.Gdip.GdipDisposeImage(new HandleRef(this, nativeImage)) and then SuppressFinalize.
RickZeeland 3 days ago
   
System.GC.Collect() forces the garbage collector to run, but this is not advised by Microsoft.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web04 | 2.8.190114.1 | Last Updated 12 Jan 2019
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100