簡體   English   中英

如何處理C#內存分配(地址空間碎片)

[英]How to deal with C# memory allocation (Address space fragmentation)

我遇到以下問題。 使用C#(和XNA),我嘗試分配一個中等大小(〜55 MB)的Color []類型的數組。 顏色是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位平台中。 我建議使用某種零散的或“分塊的”數組類,如下所示:

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

當然會損失性能。 但是,這取決於您的特定應用程序以及訪問該陣列的頻率。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM