【问题标题】:How to deal with C# memory allocation (Address space fragmentation)如何处理 C# 内存分配(地址空间碎片)
【发布时间】:2016-12-28 10:21:45
【问题描述】:

我遇到了以下问题。使用 C#(和 XNA),我尝试分配一个 Color[] 类型的中等大小(~55 MB)的数组。颜色是 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 位应用程序中。您是否正在为 32 位目标编译?是否有可能使其仅 64 位?
  • 这个问题太宽泛了,尤其是缺少一个好的minimal reproducible example。我确实注意到您未能在异常情况下处理您的 memoryReservation 对象。如果没有好的 MCVE,就不可能知道这是否与您观察到的问题有关。您很可能会遇到碎片问题;特别是,该数组可能分配在大对象堆中,该堆并不总是被压缩(检查GCSettings.LargeObjectHeapCompactionMode),这可能导致由于碎片而导致分配失败。如果您想要一个有用的答案,请改进您的问题。
  • 不幸的是,不能选择 64 位。

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


【解决方案1】:

这是一个常见问题,尤其是在 32 位平台中。我建议使用某种碎片或“分块”数组类,比如这个:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-23
    • 2013-12-24
    • 2011-07-25
    • 2011-06-18
    • 1970-01-01
    • 2011-12-13
    • 2017-12-09
    • 2017-06-30
    相关资源
    最近更新 更多