简体   繁体   中英

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

I'm working to make our application more performant by caching more stuff in memory. What worries me, though, is all that I'm reading about how the large object heap is not really compacted during a garbage collection, and that this can cause memory fragmentation.

I've been doing some small testing, but it seems I can't induce this problem. So here's my question: Can you show me a code snippet in C# that would, at some point, cause failure due to memory fragmentation?

Try having a look at the code snippet in this article The Dangers of the Large Object Heap and implementing this code just after the catch block of the Fill function to fragment the LOH, as outlined by cfneese posted on 11/04/2011 in the comments for the bug Large Object Heap fragmentation causes 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();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM