我正在尝试创建一个应用程序来显示在线火车picturebox
所以为了实现这个我创建了一个worker thread
为了获得在线火车位置。所以我定义了线程,如下所示:
private Thread workerThread = null;
private delegate void UpdateListBoxDelegate();
private UpdateListBoxDelegate UpdateListBox = null;
In 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();
}
The GetOnlineTrain
获取在线火车的位置,如下所示:
public void GetOnlineTrain()
{
try
{
while (true)
{
TimeTableRepository objTimeTableREpository = new TimeTableRepository();
OnlineTrainList = objTimeTableREpository.GetAll().ToList();
objTimeTableREpository = null;
Invoke(UpdateListBox);
}
}
catch(Exception a)
{
}
}
最后的函数将在线火车绘制在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
有时我的火车Disappears
来自picturebox
。为了第一次绘制在线火车,我在上面绘制了火车地图(线路、车站...)picturebox
有尺寸x=A
and y=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
我的应用程序退出。
此致