繁体   English   中英

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

[英]How to deal with C# memory allocation (Address space fragmentation)

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

我已经在使用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;
    } 

这是一个常见问题,特别是在32位平台中。 我建议使用某种零散的或“分块的”数组类,如下所示:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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