2

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.

Elnaz Yousefi
  • 195
  • 1
  • 3
  • 17
  • afaik GC defrags it automatically when you try to allocate new memory and it realizes that there is no more big enough chunk. Unless you get a real problem with that (e.g. the defrag taking too much time when it finally happens), you shouldn't take care of this yourself. – René Vogt Aug 30 '16 at 13:15
  • You'll have to dig deeper. This happens when objects in your program are pinned for a very long time. Or if the finalizer thread is deadlocked. – Hans Passant Aug 30 '16 at 13:16
  • @RenéVogt I got a real problem with this unusual growing size! so I decided to handle it myself. I saw about 2G generation 2 Heap but only about 30M is used and the rest of that is fragmented and free. – Elnaz Yousefi Aug 30 '16 at 13:19
  • What version of .net framework - GC has changed in 4.5 – PhillipH Aug 30 '16 at 13:56
  • .NET Framework 4.5.1 – Elnaz Yousefi Aug 30 '16 at 14:32
  • Was this issue ever resolved? – user2864740 Nov 04 '18 at 23:27
  • 1
    Our windows service had memory leakage and by disposing these buffers, we handled the problem. so, we didn't need any other defragmentation. – Elnaz Yousefi Nov 05 '18 at 13:51

2 Answers2

1

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

Max CHien
  • 133
  • 1
  • 8
0

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~

Max CHien
  • 133
  • 1
  • 8