2016-08-21 63 views
0

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

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

这通常发生在32位应用程序中。你在编译32位目标吗?任何可能使它只有64位? – Jaime

+1

这个问题太广泛了,尤其是缺乏一个好的[mcve]。我注意到你没有把你的'memoryReservation'对象抛弃在一个异常上。如果没有一个好的MCVE,就不可能知道它是否与你观察到的问题有关。你可能会遇到碎片问题;特别是数组很可能分配在大对象堆中,而这个堆并不总是被压缩(检查'GCSettings.LargeObjectHeapCompactionMode'),这可能导致由于分片导致的分配失败。改善你的问题,如果你想有用的答案。 –

+0

不幸的是,使它成为64位不是一种选择。 –

回答