Finding memory leaks in C# application

喜你入骨 提交于 2019-12-01 06:33:43

问题


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 :

  1. The application grows until reaching up to 4 GB in RAM when usually it "should" stay at around 500 MB. Consequence -> it crashes!
  2. The application grows slowly up to 1200 MB (30 minutes) and then abruptly shrinks to 500 MB (in one second)... and this process repeats itself every now and then. Can this be Garbage Collector in action ?

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# ?

I've also found the application NetMemoryProfiler4 but I would prefer to use embedded logging if it's possible !


回答1:


You need memory profiler to debug such problems. For example:

  • CLR Profiler
  • .Net Memory Validator
  • GlowCode
  • ANTS Memory Profiler

Also see suggestions from the other question about memory leaks.

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.




回答2:


Maybe Process class is the right thing you are searching.
Use Process myProcess = Process.GetCurrentProcess() to get current process.
Then you can use myProcess´s properties like WorkingSet64, PrivateMemorySize64 and so on.



来源:https://stackoverflow.com/questions/12474321/finding-memory-leaks-in-c-sharp-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!