Using Visual C# 2008 Exp Edition, I’ve noticed that with my project loaded the process is consuming ~70,000K of memory. After a few hours this builds up to about ~500,000K.
At this point a UserControl containing a PictureBox (within a Panel) shows a memory error in Visual C# Express. The picture box contains a bitmap and grid of rectangles, drawn with System.Drawing.Graphics.
Here’s the code:
This segement occurs just once when the UserControl is initialised.
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;
This piece of code is quite frequent:
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();
Am I not releasing resources properly? How can I do this correctly?
You’re not releasing your bitmap. Depending on how often your code runs the garbage collector may not be able to keep up.
You will want to check other parts of your code that use GDI for unreleased resources as well.