Finding memory leaks in C# application

2020-02-13 01:50发布

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 !

2条回答
不美不萌又怎样
2楼-- · 2020-02-13 02:14

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

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.

查看更多
乱世女痞
3楼-- · 2020-02-13 02:18

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.

查看更多
登录 后发表回答