在图片框中绘制列车时,c#中的内存不足exception

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

因此,要实现这一点,我创建一个worker thread来获得在线列车位置。所以我定义了线程,你可以在这里看到:

 private Thread workerThread = null; private delegate void UpdateListBoxDelegate(); private UpdateListBoxDelegate UpdateListBox = null; 

Form_load我称之为:

  UpdateListBox = new UpdateListBoxDelegate(this.UpdateStatus); // Initialise and start worker thread workerThread = new Thread(new ThreadStart(this.GetOnlineTrain)); workerThread.Start(); 

我委托处理的方法是:

 private void UpdateStatus() { foreach (TimeTable onlineTrain in OnlineTrainList.ToList()) { if (lstSensorLeft.Count != 0 || lstSensorRight.Count != 0) { pictureBoxonlineTrain.Image = null; DrawOnlineTrain(); } else { pictureBoxonlineTrain.Image = null; } } this.Invalidate(); } 

GetOnlineTrain获取在线火车的位置,如下所示:

 public void GetOnlineTrain() { try { while (true) { TimeTableRepository objTimeTableREpository = new TimeTableRepository(); OnlineTrainList = objTimeTableREpository.GetAll().ToList(); objTimeTableREpository = null; Invoke(UpdateListBox); } } catch(Exception a) { } } 

最后的function是在图片picturebox上绘制在线列车:

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

但我的应用程序花费了大量的内存,有时我得到了Out of memory exception ,有时我的列车从图片picturebox Disappears了。 为了绘制在线火车第一次我在图片picturebox上绘制火车(线,站,…)的地图,大小为x=Ay=b之后,我创建了另一个相同大小的图片picturebox ,并将第二个图片picturebox放在第一个图片picturebox使用此代码:

  pictureBoxonlineTrain.Parent = pictureBoxMetroMap; 

我想也许我的代码的某些部分会消耗大量的内存,我应该使用Dispose或其他东西。有时我出现out of memory exception并且错误是由graphic引起的我不确定!有时我从这一行得到了错误:

  map = new Bitmap(pictureBoxonlineTrain.Size.Width, pictureBoxonlineTrain.Size.Height); 

能不能给我一些帮助。有没有我应该处理的课程?或者问题是由我的实施引起的

我跟踪taskmanager的内存使用情况,有时我的使用率达到1,666,881 ,我的应用程序退出。

最好的祝福

处理您不再需要的位图。 它们消耗大量的非托管内存。 GC不知道非托管内存,也无法根据无法访问的非托管内存触发收集。