Is it important to dispose SolidBrush and Pen?

后端 未结 6 847
别跟我提以往
别跟我提以往 2021-01-04 00:55

I recently came across this VerticalLabel control on CodeProject.

I notice that the OnPaint method creates but doesn\'t dispose Pen and SolidBrush objects.

D

6条回答
  •  再見小時候
    2021-01-04 01:16

    FWIW, in GDI there are "stock" objects. When you create a stock object you don't have delete it because it is "owned" by the OS.

    You probably already know about stock objects, but here is a link that goes into some detail.

    I don't know if there are similar "stock" objects in GDI+. I have just searched briefly and haven't found any references to such.

    As a test I wrote a small WinForms program with a timer callback (set to fire every 10 milliseconds) like this:

    private void timer1_Tick(object sender, EventArgs e)
    {
      byte r = (byte)rnd.Next(0, 256);
      byte g = (byte)rnd.Next(0, 256);
      byte b = (byte)rnd.Next(0, 256);
    
      System.Drawing.SolidBrush sb = new SolidBrush(Color.FromArgb(0,r,g,b));
    }
    

    If I let it run, it will slowly consume memory. By watching TaskManager (not the most accurate way to gauge it), memory usage tends to grow by (on my machine, built with .NET 4.0 VS2010, Release) about 20k bytes per Task Manager update (at highest update rate). If I call Dispose on the brush, memory usage tends to grow by about 8k per Task Manager update.

    Hardly a definitive test, but it seems to point to greater memory usage over time if the SolidBrush is not disposed. Interestingly, I neither Handles nor GDI Objects increased at all as the test ran (in either case). Based on past experience with leaking GDI resources, I was expecting to maybe see GDI Objects growing, particularly in the non-Dispose case.

    Anyway, maybe this was informative, maybe not.

提交回复
热议问题