如何真正配置内存 [英] How to really dispose memory

查看:93
本文介绍了如何真正配置内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在屏幕上创建了许多表单,并为每个表单分配了大小调整事件.
resize事件将在位图上绘制一个矩形,然后获取
此位图中的一个IntPtr hBM,将此hBM分配给form_input
backgroupimage如下.

I create many forms on Screen, and assign resize event to each form.
the resize event will draw a rectangle to a bitmap, and then get
an IntPtr hBM from this bitmap, assign this hBM to form_input
backgroupimage as follow.

void form_Resize(object sender, EventArgs e)
{
  Form Form_Input = (Form)sender;
  Rectangle Rec = Form_Input.ClientRectangle;
  Bitmap bm = new Bitmap(Rec.Width, Rec.Height);
  Graphics G = Graphics.FromImage(bm);
  Brush B = new SolidBrush(Form_Input.BackColor);
  G.FillRectangle(B, Rec);
  IntPtr hBM = bm.GetHbitmap();
  Form_Input.BackgroundImage = Image.FromHbitmap(hBM);
  G.Dispose();
  bm.Dispose();
}



当我多次调整窗体的大小时,它将弹出错误消息
的"OutOfMemoryException".

为什么会发生?! G.Dispose()和bm.Dispose()的行不能工作
真正配置内存好吗?我该如何解决这个问题?谢谢.



when I resize one of the Form many times, it then will pop up error message
of ''OutOfMemoryException''.

Why it happens ?! does the line of G.Dispose() and bm.Dispose() can not work
well to really dispose memory ? How can I solve the problem ? Thanks.

推荐答案

此代码不正确,因为在发生异常的情况下它不会调用Dispose,因此应使用try-finally块.另外,不设置刷子.最好的方法是使用using语句(不要将其与using子句混淆):
This code is not correct because it does not call Dispose in case of exception, so a try-finally block should be used. Also, a brush is not disposed. The best way to do it is using using statement (don''t mix it up with using clause):
using (Bitmap bm = new Bitmap(Rec.Width, Rec.Height)) {
    using (Brush B = new SolidBrush(Form_Input.BackColor)) {
        using (Graphics G = Graphics.FromImage(bm)) {
            //use bm, B, G here...
        } // G.Dispose is called automatically
    } // B.Dispose is called automatically
} // bm.Dispose is called automatically


请参阅 http://msdn.microsoft.com/en-us/library/yh598w02.aspx [ ^ ].

—SA


See http://msdn.microsoft.com/en-us/library/yh598w02.aspx[^].

—SA


您是否也尝试过处理刷子?
另外,(更重要的是)您是否查看过 GetHbitmap方法 [
Have you tried Disposing of the Brush as well?
Plus, (and more importantly) have you looked at the GetHbitmap method[^] documentation? Somehow I doubt it...

"You are responsible for calling the GDI DeleteObject method to free the memory used by the GDI bitmap object. For more information about GDI bitmaps, see Bitmaps in the Windows GDI documentation."


检查此答案

.Net应用程序中的内存泄漏 [
Check this answer

Memory Leaks in .Net Application[^]


这篇关于如何真正配置内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆