2016-08-21 82 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位不是一種選擇。 –

回答