Possible bug with .net winforms, or am I just missing something? GDI object leak

左心房为你撑大大i 提交于 2019-12-04 20:19:18

Try adding this to the top of your dispose method (in the designer file):

comboBox1.DataSource = null;

I see two potential issues here:

  1. If you create an instance of an object that implements IDisposable, you must call the Dispose method on it, or wrap its use in a using block. Form implements IDisposable, so your code should look like the following:

        using (Form myform = new Form())
        {
            myform.Show();
        }   //frees resource by calling Dispose automatically
    

    otherwise, you will see the memory leaks you see here, because you are creating new instances of your Form, but then you are never freeing its resources. Garbage collection might eventually free up Windows resources for you in WinForms, due to the way that finalizers are written in the BCL, but calling Dispose will do it immediately.

  2. You are creating a new Font object and assigning it to the Font property each time your form is initialized. Not that this is necessarily bad (designer generated code does this copiously), but each new Font instance occupies a GDI handle, which will not be freed automatically unless you call Font.Dispose. My guess is that you are leaving another Font object behind that might not be getting Disposed properly. You may want to optimize this in some way (such as by sharing a Font instance) if you are making huge numbers of these objects. In at least one case, not calling Dispose on fonts will cause this memory leak.

You are using Font object which is an GDI object and not disposed until you dispose it. Either use Font object with using statement, or call Font.Dispose on FormClose event.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!