简体   繁体   中英

Bitmap and picturebox cause out of memory exception

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 ?

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM