Is it important to dispose SolidBrush and Pen?

后端 未结 6 846
别跟我提以往
别跟我提以往 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:28

    I need to fix some memory leaks in an application so I've being doing some investigation. In a nutshell it seems that for most cases you get away with it with slightly higher memory use.

    Below is a pathological case. I monitor my test app in task manager (crude I know) and watched the Memory (Private Working Set), Handles, USER Objects and GDI Objects columns. Button1 clicks cause higher memory use than Button2 clicks.

    If I click rapidly and persistently on Button1 I can cause an 'System.OutOfMemoryException' when Memory hits about 1.6GB. Button2 never goes higher than about 12MB no matter how madly or persistently I click.

    I'm on a win7 64-bit machine building a vs 2010 .net 4 client profile winforms app. Obviously you'd never normally construct millions and millions of brushes...

    Regards David

    private void button1_Click(object sender, EventArgs e) {
        for (int i = 0; i < 500000; i++) {
            SolidBrush b = new SolidBrush(Color.FromArgb(2, 32, 43, 128));
        }       
    }
    
    private void button2_Click(object sender, EventArgs e) {
        for (int i = 0; i < 500000; i++) {
            using (SolidBrush b = new SolidBrush(Color.FromArgb(2, 32, 43, 128))) {
            }
        }
    }
    

提交回复
热议问题