我正在尝试创建一个显示picturebox
中的在线列车的应用程序。
但是我的应用程序花了很多记忆,有时我从Out of memory exception
得到了Disappears
,有时我的火车picturebox
。为了首次绘制在线列车我在picturebox
上绘制了大小为x=A
和y=b
的列车(线路,车站......)地图,之后我创建了另一个picturebox
使用相同的代码将第二个picturebox
放在第一个picturebox
上:
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");
}
我认为这是我的内存异常的原因,因为每次我创建一个bitmap
和graphic
对象。我的问题是如何更改此代码,因为每个循环中的对象都会被处置?
答案 0 :(得分:2)
将您的Bitmap和Graphics放在Using语句中,它将被处理
using (map = new Bitmap(pictureBoxonlineTrain.Size.Width, pictureBoxonlineTrain.Size.Height))
{
using (Graphics graph = Graphics.FromImage(map))
{
//code goes here
}
}