c# - 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# 中会自动释放,但图像是特殊的,因为它们是 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()
. 为了简单起见,我没有在这里展示。
推荐阅读
- php - 如何在php curl中上传文件
- scala - 错误:(63, 3) 类型不匹配;找到:所需单位:双
- android - RxJava 登录并获取用户信息
- powershell - Get-Printer:找不到与参数名称“Like”匹配的参数
- javascript - 如何删除模态框内的 tbody 数据
- vb.net - 在 VB.NET 中禁用 CheckListBox 中的项目?
- docker - 无法始终将数据从主机发送到 docker 容器
- c - 创建树时出现分段错误 (C)
- react-native - 如何处理 codepush 和 Google playstore / Apple appstore 之间的潜在竞争条件
- python - 根据多列的总和顺序复制行