问题
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 :
- The application grows until reaching up to 4 GB in RAM when usually it "should" stay at around 500 MB. Consequence -> it crashes!
- 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