I have a method that loops through a data collection, builds bitmaps based on the data in the collection retrieved from the database, and finally adds the built bitmaps in a collection that I call DoorSchedules.
In my loop if I call .dispose on my graphics I receive an error. This error does not happen when I do not call the .dispose method that belongs to the Graphics object.
When should I call dispose on the graphics object when looping, do I create a new graphics object for each loop?
The code works below, until I un-comment the dc.Dispose.
DoorSchedules schedules = new DoorSchedules();
for (byte i = 0; i < elevation.Bays.Count; i++)
{
if (elevation.Bays[i].HasDoor.Value)
{
for (byte ii = 0; ii < elevation.Bays[i].Doors.Count; ii++)
{
door = elevation.Bays[i].Doors[ii];
width = getInchPx(door.WidthInches);
height = getInchPx(door.HeightInches);
Bitmap canvas = new Bitmap((int)width + DOOR_SCHEDULE_WIDTH_ADD,
(int)height + DOOR_SCHEDULE_HEIGHT_ADD);
Graphics dc = Graphics.FromImage(canvas);
..work removed for readability for stackoverflow.
schedules.Add(new DoorSchedule(canvas));
//dc.Dispose();
};
};
};
You can try enclosing your objects that require disposing in using statements, that way the resources will be released automatically when finished.
From above link:
See if something like this works for you, if it doesn’t please supply the error that you are receiving.
In looking at your previous question it looks like you abandoned the use of using because you ended up disposing your Bitmap, if this is the same code you can try creating a Clone of your Bitmap instead.
so in your case it would look something like: