【发布时间】: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