本文介绍了位图和图片框事业内存溢出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个显示在网上火车的应用程序图片框

I am trying to create an application that shows the online trains in picturebox.

但我的应用程序花费了大量的记忆,有时我得到了内存不够的异常键,有时我的火车消失图片框。要绘制在线列车第一次我画的火车在地图上图片框(线路,车站,...)与大小 X = A 计算y = b 之后,我创建另一个图片框具有相同的大小,并把第二个图片框首次图片框:

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");
            } 

,我认为这是我的记忆异常的原因,因为每次我创建一个位图图形对象。我的问题是,我怎样才能改变这种code作为对象每次循环处理?

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 ?

推荐答案

把你的位图图形Using语句内,它将被处置

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

这篇关于位图和图片框事业内存溢出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 20:20