I have a lot of unused memory allocated to .net

2.4k views Asked by At

running ANTS memory profiler I see that I have a lot of unused memory allocated to .net.

How do I determine what is causing this?

I have put a screenshot of the summary report generated by ANTS here: ANTS Summary report

Thanks Thomas

1

There are 1 answers

0
Murometz80 On

I had the same issue when I ran about 20 Selenium tests in parallel. After analyzing the issue I narrowed it down that it is probably due to a particular method allocating a lot of memory and GC probably was not cleaning it in time for parallel calls, so as the discussion under the question suggested I imagine it created a swiss cheese.

I first added this code to analyze this problem as suggested here https://www.codeguru.com/dotnet/memory-leaks-dot-net/

GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();

Sure enough unused memory allocated to .Net decreased from 500MB to 50MB

But this code is not advisable since it can cause deadlocks so instead my solution is to get allocated bytes in the beginning of the method, then at the end and alert GC about bytes allocated during that method call. As a result I saw memory consumption slowly decreasing to 50MB

public async Task<IActionResult>  MemoryConsumingMethod()
{
   var allocatedBytesStart = GC.GetTotalAllocatedBytes();
   ...
   //main content
   var model = MyViewModel(){...}
   ...
   var allocatedBytesEnd = GC.GetTotalAllocatedBytes();
   GC.AddMemoryPressure(allocatedBytesEnd - allocatedBytesStart);

   return View(model);
}