首页 > 解决方案 > System.OutOfMemoryException:内存不足

问题描述

我正在制作一个使用 Graphics 从文件夹中随机绘制图片的游戏。 这里是:

这是针对 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#graphics

解决方案


正如其他人所说,您有内存泄漏,因为您没有处理图像。注意:通常未使用对象的内存在 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(). 为了简单起见,我没有在这里展示。


推荐阅读