Force .NET GC to compact or defragment generation 2 heap?

3.6k Views Asked by At

We wrote a windows service by C# in .NET framework, after some hours we noticed that the size of heap generation 2 is growing unordinary. Most of this space is free and dotMemory Profiler showed us that we have about 90% fragmentations on this generation. How can I enforce .NET GC to compact this space? It means that GC could free this space but It couldn't compact it for further usage.

2

There are 2 best solutions below

0
Max CHien On

Generation 2 heap is small object heap, so basically gen 2 will compact too(Since we call GC.Collect())

And Large Object Heap(>=85K) won't compact automatically. I want to compact LOH, you can use .Net Framework.

So have make sure which heap you used~

0
Max CHien On

Since generation 0,1,2 will compact and delete by GC it's self,

Guess that object allocate on Large object heap(LOH, Object size >= 85K)

So, you can try LargeObjectHeapCompactionMode, it can compact loh

GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect();  

Ref : MSDN