Bitmap and picturebox cause out of memory exception

拟墨画扇 提交于 2019-12-12 02:15:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!