this.Dispose()关闭后不会释放由表使用的内存。 [英] this.Dispose() doesn't release memory used by Form after closing it.

查看:1029
本文介绍了this.Dispose()关闭后不会释放由表使用的内存。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在其中点击某些按钮创建一个从第二表单对象Windows窗体应用程序。在用户关闭这个第二个表格,这份表格使用的内存(根据任务管理器)不会被释放。

I have a Windows Form Application in which clicking certain buttons create objects from a 2nd Form. On closing this 2nd Form by the user, the memory used by this form is not released (according to Task Manager).

我试着用此.dispose()退出按钮, this.close()窗口2 = NULL 在主代码,并试图通过代码处理之前,从这种形式的清除所有控件。这一切都已经工作,每次用户点击该按钮,由以前的实例未公布使用的应用程序的增加和内存的内存使用量。

I tried using this.dispose() on exit button, this.close(), form2 = null in the main code, and tried clearing all controls from this form by code before disposing. None of this has worked and every time the user clicks the button, the memory usage by the application increases and memory used by the previous instance is not released.

我拿什么用它来解决这个问题?

What shall I use to solve this problem?

推荐答案

调用的Dispose 不会清理由对象使用的内存。 的Dispose ,就是要用来运行用户定义的代码版本未自动释放资源 - 如文件句柄,网络手柄,数据库连接等。

Calling Dispose will not clean up the memory used by an object. Dispose is meant to be used to run user defined code that releases resources that are not automatically released - like file handles, network handles, database connections etc.

可能的罪魁祸首可能是第二种形式连接事件是外面(也许是第一种形式?)对象和从未unattaching他们。

The likely culprit is probably the second form attaching events to objects that are outside it (perhaps the first form?) and never unattaching them.

如果您在第二种形式的任何事件,它们卸装在你的OnClose覆盖 - 这将使第二种形式符合垃圾收集

If you have any events in the second form, unattach them in your OnClose override - that will make the second form eligible for garbage collection.

请注意,.NET垃圾收集器是相当不可预测的,这可能清理所有有资格的收集旧实例之前创建的对象的几个实例。 A到知道肯定(而不是诉诸内存分析器)的方式是把一个断点终结:

Note, .NET garbage collector is quite unpredictable and it might create a few instances of an object before cleaning up all the older instances that were eligible for collection. A way to know for sure (without resorting to memory profilers) is to put a breakpoint in the finalizer:

public class MyForm : Form {
  ~MyForm() {
    //breakpoint here
  }
}

如果终结器被调用那么这个类是确定的,如果不是,你仍然有泄漏。你也可以给GC一踢 - 但只是为了排除故障 - 不要留在生产中这段代码 - 通过启动GC:

If the finalizer gets called then this class is OK, if not, you still have a leak. You can also give GC a "kick" - but only for troubleshooting purposes - do not leave this code in production - by initiating GC:

GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();



把上面的代码的地方,你运行后关闭和处置的第二种形式。你应该打在 MyForm的终结断点。

这篇关于this.Dispose()关闭后不会释放由表使用的内存。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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