Can you give me an example that causes memory fragmentation in .NET.

I am working to make our application more efficient by caching more material in memory. However, what bothers me is that I read about how the heap of a large object does not actually compact during garbage collection, and this can lead to memory fragmentation.

I did a little testing, but it seems like I cannot cause this problem. So here is my question: can you show me a C # code snippet that might at some point cause a crash due to memory fragmentation?

+5
source share
1 answer

" " catch Fill LOH, cfneese, 11/04/2011 OutOfmemoryException

        unsafe
        {
            var w = new StreamWriter(@".\test.txt");
            for (int i = 0; i < count; i++)
            {
                var handle = GCHandle.Alloc(smallBlocks[i], GCHandleType.Pinned);
                w.WriteLine(String.Format("{0,10}\t{1,10}", i, handle.AddrOfPinnedObject()));
                handle.Free();
            }
            w.Close();
        }
+2

All Articles