0

I'm trying to find a memory leak in a .NET 5.0 Web API application hosted in Kubernetes. I have read some tips and tricks and found a good advice here: https://www.tessferrandez.com/blog/2005/11/25/dumpheap-stat-explained.html

A good trick if you want to know where you leak and want to avoid looking through a lot of data that will be garbage collected soon is to run a stress-test, then induce a GC by calling GC.Collect(3), take a memory dump, then stress it a bit more, induce a GC again and take another memory dump and compare the objects on the heap.

I really don't want to create a special debugging method for the app and redeploy it to the test environment. So can I trigger garbage collection for Gen 2 from outside of the app?

Yuriy Gavrishov
  • 4,341
  • 2
  • 17
  • 29

2 Answers2

2

You need to analyze what is causing the memory leak. DotMemory is a great tool that analyzes the snapshots taken and you can analyze differences between allocations and find the root cause.

The best practise is to not force a garbage collection in most cases. CLR is smart enough to clean up memory for you when it is appropriate.

But, if you have the necessity to force GC, you can do either:

A. In your API controller implement Dispose method of ApiController and add this line to it.

GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);

Every time request is served and controller is about to be disposed, this will cause GC collection, it might hinder the performance though.

B. You can create the API endpoint something like api/optimize and implement it to force GC collection as well.

NazaRN
  • 399
  • 1
  • 5
0

You probably want to use a memory debugger. The one I have used can both trigger a GC as well as capturing snapshots of the memory and presenting the result in a way to make it easy to find leaks.

You could probably write some small tool to trigger a GC yourself, but if you get paid for your time, it is probably more cost effective to just buy the appropriate tooling that helps solve your problem. Here is a post about different profilers, but contrary to the accepted answer I would say dotMemory works perfectly fine, at least in 2022.

JonasH
  • 28,608
  • 2
  • 10
  • 23