Skip to main content
 首页 » 编程设计

c#之Visual C#,进程不断增长,直到出现与使用循环绘制图形的 UserControl 相关的内存错误

2024年02月23日14artech

使用 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(); 

我没有正确释放资源吗?我怎样才能正确地做到这一点?

请您参考如下方法:

您没有发布您的位图。根据您的代码运行频率,垃圾收集器可能无法跟上。

using (Bitmap myBitmap = new Bitmap(a, b)) 
using (Graphics g = Graphics.FromImage(myBitmap)) { 
    for (int x = 0; x <= e - 1; x++) { 
        for (int y = 0; y <= f - 1; y++) { 
            g.DrawRectangle(Pens.LightBlue, g, h, i); 
        } 
    } 
 
    ScorePictureBox.Image = myBitmap; 
} 

对于未发布的资源,您还需要检查使用 GDI 的代码的其他部分。