Click here to Skip to main content
15,887,585 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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 11-Jan-19 23:50pm

1 solution

 
Share this answer
 
v2
Comments
Member 11799596 12-Jan-19 10:28am    
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 12-Jan-19 10:50am    
If you are calling from C# it may have to do with the Garbage Collector, this can take some time before cleanup.
Member 11799596 12-Jan-19 12:51pm    
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 12-Jan-19 13:12pm    
System.GC.Collect() forces the garbage collector to run, but this is not advised by Microsoft.
Member 11799596 16-Jan-19 13:47pm    
I am still not clear about the reason why after calling Dispose on Bitmap, GDI object count is not getting reduced.

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


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900