Search code examples
c#.netwinformsc#-4.0dispose

Efficient way of reusing or disposing custom fonts in c#


We have C# form application, which uses lot of controls and custom font with different sizes in each of them. The problem is with the ever growing FONT gdi object count which causes OutOfMemory Exception(once it crosses 10,000 count - tested this with Bear GDI usage) whenever the controls are recreated. I had tried below options, but the font gdi does not stay consistent:

  1. Reuse each font of specific font type/size by declaring it as static variable in a static class

    static Font Robo_13Reg_Font= new Font("Roboto", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(0)));

  2. Create a local font variable and dispose once it's use is done

  3. Reuse font from a label to the required control and dispose the label, as in below code

 public static void getRobo_13Reg_Font(Control addFontTo)
    {
        try
        {
            if (Robo_13Reg_Font == null)
            {
                Robo_13Reg_Font = new Label();
                Robo_13Reg_Font.Font = new Font("Roboto", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(0)));
            }
            addFontTo.Font = Robo_13Reg_Font.Font;
            Robo_13Reg_Font.Dispose();
            Robo_13Reg_Font = null;
        }
        finally
        {
        }
    }

Appreciate all your inputs!


Solution

  • Check if you are creating numerous ToolTip instances(new ToolTip) and assigning font for the tooltip in your app - This also would create font GDI objects for each tooltip instance being created, as i had similiar problem with it.