Force garbage collection of arrays, C#

This is not an exact answer to the original question, “how to force GC’, yet, I think it will help you to reexamine your issue.

After seeing your comment,

  • Putting the GC.Collect(); does seem to help, altought it still does not solve the problem completely – for some reason the program still crashes when about 1.3GB are allocated (I’m using System.GC.GetTotalMemory( false ); to find the real amount allocated).

I will suspect you may have memory fragmentation. If the object is large (85000 bytes under .net 2.0 CLR if I remember correctly, I do not know whether it has been changed or not), the object will be allocated in a special heap, Large Object Heap (LOH). GC does reclaim the memory being used by unreachable objects in LOH, yet, it does not perform compaction, in LOH as it does to other heaps (gen0, gen1, and gen2), due to performance.

If you do frequently allocate and deallocate large objects, it will make LOH fragmented and even though you have more free memory in total than what you need, you may not have a contiguous memory space anymore, hence, will get OutOfMemory exception.

I can think two workarounds at this moment.

  1. Move to 64-bit machine/OS and take advantage of it 🙂 (Easiest, but possibly hardest as well depending on your resource constraints)
  2. If you cannot do #1, then try to allocate a huge chuck of memory first and use them (it may require to write some helper class to manipulate a smaller array, which in fact resides in a larger array) to avoid fragmentation. This may help a little bit, yet, it may not completely solve the issue and you may have to deal with the complexity.

Leave a Comment