位图和图片框导致内存不足异常

时间:2014-07-06 04:30:43

标签: c# graphics bitmap dispose using-statement

我正在尝试创建一个显示picturebox中的在线列车的应用程序。

但是我的应用程序花了很多记忆,有时我从Out of memory exception得到了Disappears,有时我的火车picturebox。为了首次绘制在线列车我在picturebox上绘制了大小为x=Ay=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");
            } 

我认为这是我的内存异常的原因,因为每次我创建一个bitmapgraphic对象。我的问题是如何更改此代码,因为每个循环中的对象都会被处置?

1 个答案:

答案 0 :(得分:2)

将您的Bitmap和Graphics放在Using语句中,它将被处理

using (map = new Bitmap(pictureBoxonlineTrain.Size.Width, pictureBoxonlineTrain.Size.Height))
{
    using (Graphics graph = Graphics.FromImage(map))
    {
//code goes here
    }
}