如何避免c#.net中的内存泄漏 [英] how to avoid memory leak in c#.net

查看:91
本文介绍了如何避免c#.net中的内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




我用c#.net编写了一个Windows服务,它将一起运行几天

我尝试访问数千个文件使用以下代码的文件夹:



string [] files = Directory.GetFiles(文件夹,*。*);



文件夹将有20,000个压缩文件或更多。这部分代码内存每次都高达5000k。



为了避免内存上升,什么将是访问该文件夹而不实际将所有文件加载到内存中的解决方案。



谢谢

Hi
I have written a windows service using c#.net that will keep running for days together
I try to access thousands of files in a folder using below code:

string[] files = Directory.GetFiles(folder, "*.*" );

folder will have 20,000 zipped files or more.This part of code memory goes up to 5000k everytime.

To avoid the memory from going up,what would be the solution to access the folder without actually loading all files into memory.

Thanks

推荐答案

检查您的架构。这是.NET中内存泄漏的一般规则。随机泄漏的可能性要小得多,大多数泄漏都是由于错误的设计/架构造成的。请看我过去的答案:

摆脱导致内存不足的公共静态列表的最佳方法 [ ^ ],

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

WPF数据绑定中的内存泄漏 [ ^ ],

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

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



如需进一步的想法,我需要知道你将如何处理20,000个文件。我无法相信任何人需要同时使用它们,甚至看到它们。因此,您需要某种虚拟化。例如,对于UI,您可能希望仅在需要下一部分时使用分页,搜索文件和加载文件名。但是,对我而言,拥有所有这些文件的整个想法看起来都很值得怀疑。在不知道你的目的的情况下,我不能建议你做任何其他选择,但几乎可以肯定它们确实存在。



-SA
Review your architecture. This is the general rule for the memory leaks in .NET. Random leaks are much less likely, most of the leaks are due to wrong design/architecture. Please see my past answers:
Best way to get rid of a public static List Causing an Out of Memory[^],
Memory management in MDI forms[^],
Memory leak in WPF DataBinding[^],
deferring varirable inside the loop can cuase memory leak?[^],
Garbage collectotion takes care of all the memory management[^].

For further ideas, I would need to know what are you going to do with 20,000 files. I cannot believe anyone need to use them at the same time, or even see them. Hence, you need some kind of virtualization. For example, with UI you may want to use paging, searching for files and loading file names only when the next portion is required. However, to me, the whole idea to have all these files look quite questionable. Without knowing your purpose, I cannot suggest you any alternative but almost sure they do exist.

—SA

这篇关于如何避免c#.net中的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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