簡體   English   中英

System.OutOfMemoryException:內存不足

[英]System.OutOfMemoryException: Out Of Memory

我正在制作一個使用“圖形”從文件夾中繪制隨機圖片的游戲。 這里是:

這是針對C#的游戲

public static int cookiecount;
public static Random random = new Random();
public static string[] files = Directory.GetFiles(Application.StartupPath, "*.png");
public static Image im;

public static void Draw(System.Drawing.Graphics g, int x, int y)
{
    try
    {
        im = Image.FromFile(files[random.Next(0, files.Count())]);

        g.DrawImage(im, x, y, 40, 40);
    }
    catch(Exception ee) {
        MessageBox.Show("Error! " +ee.Message + " " + ee.Source + " " + ee.HelpLink,
            "Oh No", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }

    cookiecount++;
}

它輸出一個錯誤,指出:

System.OutOfMemoryException:內存不足

正如其他人所說,由於不處理圖像,因此存在內存泄漏。 注意:通常,未使用的對象的內存會在C#中自動釋放,但是圖像是特殊的,因為它們是COM對象,即非.NET對象。

一次又一次地加載圖像,而不是一遍又一遍地加載圖像。 由於在整個游戲中會使用相同的圖像,因此您無需處理它們。

public static int cookiecount;
public static Random random = new Random();
public static Image[] images;

// Call this once at program start.
public static LoadImages()
{
    string[] files = Directory.GetFiles(Application.StartupPath, "*.png");
    images = new Image[files.Length];
    for (int i = 0; i < files.Length; i++) {
        images[i] = Image.FromFile(files[i]);
    }
}

public static void Draw(System.Drawing.Graphics g, int x, int y)
{
    int index = random.Next(0, images.Length);
    g.DrawImage(images[index], x, y, 40, 40);

    cookiecount++;
}

對於數組,請使用Length屬性,而不要調用Count()擴展方法。 效率更高。

另外,異常處理應移至LoadImages() 為了簡單起見,這里沒有顯示。

暫無
暫無

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

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