我正在尝试使用 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)
{
}
}
最后的功能是在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
和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
,我的应用程序退出。
祝你好运
答案 0 :(得分:3)
处理您不再需要的位图。它们消耗大量的非托管内存。 GC不知道非托管内存,也无法根据无法访问的非托管内存触发收集。