如何在表单关闭时释放内存? [英] How to release memory on form closing?

查看:88
本文介绍了如何在表单关闭时释放内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我正在使用C#windows应用程序,在按钮单击中我使用数据表从数据库中获取大数据并将其分配给网格虽然这个系统使用了大量的内存。当我关闭此表单时,系统不会立即释放内存。与此同时,我的最终用户一次又一次打开相同的表单

导致Out of Memory Exception。



请建议一个这个问题的解决方案。



我尝试了什么:



In表单关闭我试过这个.Dispose(),在将数据表作为数据源分配给网格后,我将数据表重新初始化为null

Hi,

I am working on C# windows application, where in a button click I get large data from database using data table and I assign it to a grid.While doing this system utilizes lot of memory. When I close this form, system is not releasing memory immediately. In the mean time my end user opens the same form again and again
resulting in "Out Of Memory Exception".

Please suggest a solution for this issue.

What I have tried:

In form closing I tried this.Dispose(), After assigning data table to grid as data source i reinitialized data table as null

推荐答案

如果您在班级中持有对象,如DataTables等包含大量内存或其他资源(如图形句柄等),然后在完成后单独处理它们。否则,GC将不会自动处理内存占用对象,直到内存不足为止。



但.NET中的无效对象出现内存不足错误很少见,即使你确实使用了大量的内存,GC也应该把它释放出来 - 这样你很可能会占用资源。例如,检查您的表单是否有绘画:如果您正在创建字体,图形上下文,画笔,SQL连接等,而不是处理它们,那么它们会在GC需要被真实内存激活之前提供相同的错误条件。
If you are holding objects in your class, such as DataTables and so forth which contain a lot of memory or other resources (such as graphics handles and similar) then Dispose each of them individually when you are finished with it. Otherwise, the GC won't automatically dispose of memory hogging objects until you run out of memory.

But an "Out of memory" error for nulled objects in .NET is rare, even if you do use a lot of memory, the GC should free it up - it's a lot more likely that you are hogging resources instead. For example, check your form for painting: if you are creating fonts, graphics context, brushes, SQL connections, etc. and not disposing them then they will give the same error long before the GC needs to be activated by a "real" memory condition.


对,你不可能给你一个通用的建议,但你需要先学习如何使用和回收内存,以及使用什么配置。请查看我过去的答案:

WPF DataBinding中的内存泄漏 [ ^ ],

MDI表格中的内存管理 [ ^ ],

摆脱公众的最佳途径静态列表导致内存不足 [ ^ ],

推迟循环中的变量会导致内存泄漏吗? [ ^ ],

Garbage collectotion负责所有内存管理 [ ^ ]。



只有一个想法在这些答案中详细解释:有些人认为内存泄漏在内存管理中是不可能的系统,但事实并非如此。



-SA
Right, it's impossible to give you a general advice, but you need to start with learning how memory is used and reclaimed, and what disposing is used for. Please see my past answers:
Memory leak in WPF DataBinding[^],
Memory management in MDI forms[^],
Best way to get rid of a public static List Causing an Out of Memory[^],
deferring varirable inside the loop can cuase memory leak?[^],
Garbage collectotion takes care of all the memory management[^].

Just one thought explained in detail in those answers: some think that memory leaks are impossible in memory managed systems, but this is not exactly so.

—SA


这篇关于如何在表单关闭时释放内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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