在C#应用程序中查找内存泄漏
我在C#,Framework 4中有一个应用程序。从根本上说,该应用程序主要对事件做出反应并创建对象,释放它们,创建数据库连接并关闭它们。
I have an application in C#, Framework 4. Very basically, this application mainly react to events and creates objects, release them, create database connection and close them.
现在,我们一直看到应用程序的过程有时会以非常奇怪的方式增长。我们有两种不同的行为:
Now, we've been seeing that the application's process grows sometimes in very strange ways. We've got two different behaviors :
- 应用程序不断增长,直到通常在应该停留在大约4 GB的内存中时500 MB。后果->它崩溃了!
- 应用程序缓慢增长到1200 MB(30分钟),然后突然缩小到500 MB(一秒钟)...并且此过程每重复一次不时地。
现在,为了向我们提供有关该应用程序的更多信息,我想补充一下在我们的日志文件中,应用程序进程的大小。是否可以通过本机框架?
Now, in order to provide us with more informations about the application, I would like to add in our log files the size of the application's process. Is it possible through the native framework ? Is it possible to know an object' size in C# ?
我也找到了应用程序NetMemoryProfiler4,但如果可能的话,我宁愿使用嵌入式日志记录!
I've also found the application NetMemoryProfiler4 but I would prefer to use embedded logging if it's possible !
您需要使用内存分析器来调试此类问题。例如:
You need memory profiler to debug such problems. For example:
- CLR Profiler
- .Net Memory Validator
- GlowCode
- ANTS Memory Profiler
另请参阅有关内存泄漏的另一个问题。
基本上,这可以归结为在内存中找到不应该留在这里的对象。它可以是持有对其类的引用的事件处理程序,也可以是持有对其父级的引用的一些对象的集合,依此类推。找到根本原因后,您可能需要重组应用程序以摆脱不必要的引用。这可以像添加被遗忘的事件取消订阅一样简单,但是在不平凡的情况下,可能需要应用某些结构设计模式。这部分是针对特定应用的。
Basically, this boils down to finding the objects in memory that stay here while they shouldn't. It can be event handler holding reference to its class or some collection of objects holding references to their parents, and so on. After finding the root cause you may need to restructure your application to get rid of the unnecessary references. This can be as simple as adding forgotten event unsubscription but in non trivial cases might require applying some structural design patterns. This part is very application specific.