问题
I am trying to create an application that shows the online trains in picturebox
.
but my application spends a lot of memory and sometimes i got the Out of memory exception
and sometimes my trains Disappears
from the picturebox
. To draw online train first time i draw the map of trains (lines ,stations ,...) on picturebox
with size x=A
and y=b
after that i create another picturebox
with the same size and put the second picturebox
on first picturebox
using this code:
pictureBoxonlineTrain.Parent = pictureBoxMetroMap;
In every second the below function is executed :
public void DrawOnlineTrain()
{
Bitmap map=null;
if (OnlineTrainList.Count > 0)
{
map = new Bitmap(pictureBoxonlineTrain.Size.Width, pictureBoxonlineTrain.Size.Height);
var graph = Graphics.FromImage(map);
foreach (TimeTable t in OnlineTrainList.ToList())
{
// graph.Dispose();
Rectangle rectTrainState = new Rectangle(t.XTrainLocation.Value - 3,
t.YTrainLocation.Value - 3,
15, 15);
graph.FillRectangle(RedBrush, rectTrainState);
graph.DrawString(t.TrainId.ToString(), pictureBoxonlineTrain.Font, Brushes.White, t.XTrainLocation.Value -3, t.YTrainLocation.Value -3);
}
}
pictureBoxonlineTrain.Image = map;
// pictureBoxonlineTrain.Image.Save(@"C:\RailwayShiraz\ShirazMetro\ShirazRailWayWeb\Images\Train.jpg");
}
And i think it is the reason of my memory exception because every time i create a bitmap
and graphic
object .My question is how can i change this code as the objects dispose in every loop ?
回答1:
put your Bitmap and Graphics inside a Using statement and it will be disposed
using (map = new Bitmap(pictureBoxonlineTrain.Size.Width, pictureBoxonlineTrain.Size.Height))
{
using (Graphics graph = Graphics.FromImage(map))
{
//code goes here
}
}
来源:https://stackoverflow.com/questions/24592729/bitmap-and-picturebox-cause-out-of-memory-exception