Visual C#,进程增长,直到我收到与使用循环绘制图形的用户控件相关的内存错误

本文关键字:用户 绘制 图形 错误 内存 循环 控件 进程 Visual | 更新日期: 2023-09-27 18:33:18

使用 Visual C# 2008 Exp Edition,我注意到加载项目后,进程消耗了 ~70,000K 的内存。几个小时后,这就会增加到大约~500,000K。

此时,包含PictureBox(在Panel内)的UserControl在 Visual C# Express 中显示内存错误。图片框包含用System.Drawing.Graphics绘制的位图和矩形网格。

代码如下:

初始化UserControl时,此隔离仅发生一次。

Bitmap myBitmap = new Bitmap(a, b);
Graphics g = null;
g = Graphics.FromImage(myBitmap);
g.FillRectangle(Brushes.SteelBlue, 0, 0, c, d);
//Paint Rows & Columns
for (int x = 0; x <= e - 1; x++)
{
    for (int y = 0; y <= f - 1; y++)
    {
        g.DrawRectangle(Pens.LightBlue, g, h, i);
    }
}
//Release Resources
g.Dispose();
//Add bitmap with grid to BG
ScorePictureBox.Image = myBitmap;

这段代码非常频繁:

for (int EventIndex = 0; EventIndex <= MidiNoteDownArray.Length - 1; EventIndex++)
{
    //Paint notes to grid
    e.Graphics.FillRectangle(Brushes.LightBlue, j, k, l, m);
    e.Graphics.DrawRectangle(Pens.Purple, o, p, q, r);
}
e.Dispose();

我是否没有正确释放资源?如何正确执行此操作?rrect

Visual C#,进程增长,直到我收到与使用循环绘制图形的用户控件相关的内存错误

检查您的项目。也许您缺少参考。

可能是您正在创建的位图 - 当您替换ScorePictureBox上的图像时,您需要处理旧的图像,即:

var oldImage = ScorePictureBox.Image;
//Add bitmap with grid to BG
ScorePictureBox.Image = myBitmap;
// Dispose of previous score image if necessary
if (oldImage != null) oldImage.Dispose();

请注意双重处理 - 通常最好不要在其他项仍在引用 GDI+ 对象时释放它们。

在一般的语法说明中,您可能最好使用using语句而不是显式调用Dispose(),即:

using (Graphics g = Graphics.FromImage(myBitmap))
{
   ...
}