如何处理C#内存分配(地址空间碎片)

时间:2016-08-21 23:49:22

标签: c# c#-4.0 memory memory-management out-of-memory

我遇到了以下问题。使用C#(和XNA),我尝试分配一个类型为Color []的中等大小(~55 MB)的数组。颜色是4个字节。但是,90%的内存分配尝试由于内存不足而导致失败"尽管系统具有16 GB RAM(约12 GB可用),但例外。

我已经使用MemoryFailPoint类来保留内存(请参阅下面的代码),但这似乎无济于事。我假设我遇到了“解决碎片问题”的问题。的问题。但是我能做些什么呢?有没有办法进行碎片整理'地址空间?

    public static bool AllocateMemory(out Color[] colorBuffer, int size)
    {
        // Color has 4 bytes
        int sizeInMegabytes = (int)Math.Ceiling(((float)(size * 4) / (1024f * 1024f)));

        #region Use MemoryFailPoint class to reserve memory

        // Check that we have enough memory to allocate the array.
        MemoryFailPoint memoryReservation = null;
        try
        {
            memoryReservation =
                new MemoryFailPoint(sizeInMegabytes);
        }
        catch (InsufficientMemoryException ex)
        {
            colorBuffer = null;

            Warning.Happened("Failed to reserve " + sizeInMegabytes + " MB memory.");

            return false;
        }

        #endregion

        // Allocte memory for array
        colorBuffer = new Color[size];

        //Now that we have allocated the memory we can go ahead and call dispose
        memoryReservation.Dispose();

        return true;
    } 

1 个答案:

答案 0 :(得分:0)

这是一个经常出现的问题,特别是在32位平台上。我建议使用某种支离破碎的或者#34; chunked"数组类,如下所示:

https://blogs.msdn.microsoft.com/joshwil/2005/08/10/bigarrayt-getting-around-the-2gb-array-size-limit/

当然会有性能损失。但是,这取决于您的特定应用程序以及访问该阵列的频率。

相关问题