[英]How to deal with C# memory allocation (Address space fragmentation)
I am running into the following problem. 我遇到以下问题。 Using C# (and XNA), I try to allocate an array of moderate size (~55 MB) of type Color[].
使用C#(和XNA),我尝试分配一个中等大小(〜55 MB)的Color []类型的数组。 Color is 4 bytes.
颜色是4个字节。 However, 90% percent of the memory allocation tries fail due to an "Out of memory" exception despite the system having 16 GB RAM (~12 GB free).
但是,尽管系统具有16 GB RAM(约12 GB可用空间),但仍有90%的内存分配尝试由于“内存不足”异常而失败。
I am already using the MemoryFailPoint class to reserve the memory (see code below) but this seems to not help. 我已经在使用MemoryFailPoint类来保留内存(请参见下面的代码),但这似乎无济于事。 I assume I am running into 'address fragmentation' issues.
我假设我遇到了“地址碎片”问题。 But what can I do about it?
但是我该怎么办? Is there a way to 'defragment' the address space?
有没有办法对地址空间进行碎片整理?
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;
}
This is a frequent issue, specially in 32-bit platforms. 这是一个常见问题,特别是在32位平台中。 I suggest to use some kind of fragmented or "chunked" array class, like this one:
我建议使用某种零散的或“分块的”数组类,如下所示:
https://blogs.msdn.microsoft.com/joshwil/2005/08/10/bigarrayt-getting-around-the-2gb-array-size-limit/ https://blogs.msdn.microsoft.com/joshwil/2005/08/10/bigarrayt-getting-around-the-2gb-array-size-limit/
Of course there will be a loss of performance. 当然会损失性能。 However, it depends on your specific application and how frequently you access that array.
但是,这取决于您的特定应用程序以及访问该阵列的频率。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.