[英]Having 1 thread execute multiple methods at the same time
So I have a list with 900+ entries in C#. 所以我在C#中有一个包含900多个条目的列表。 For every entry in the list a method has to be executed, though these must go all at the same time. 对于列表中的每个条目,必须执行一个方法,尽管这些方法必须同时进行。 First I thought of doing this: 首先我想到这样做:
public void InitializeThread()
{
Thread myThread = new Thread(run());
myThread.Start();
}
public void run()
{
foreach(Object o in ObjectList)
{
othermethod();
}
}
Now the problem here is that this will execute 1 method at a time for each entry in the list. 现在问题是这将为列表中的每个条目一次执行1个方法。 But I want every single one of them to be running at the same time. 但我希望他们中的每一个都能同时运行。
Then I tried making a seperate thread for each entry like this: 然后我尝试为每个条目创建一个单独的线程,如下所示:
public void InitializeThread()
{
foreach(Object o in ObjectList)
{
Thread myThread = new Thread(run());
myThread.Start();
}
}
public void run()
{
while(//thread is allowed to run)
{
// do stuff
}
}
But this seems to give me system.outofmemory exceptions (not a suprise since the list has almost a 1000 entries. Is there a way to succesfully run all those methods at the same time? Either using multiple threads or only one? 但这似乎给了我system.outofmemory异常(不是一个惊喜,因为该列表有几乎1000个条目。有没有办法成功地同时运行所有这些方法?使用多个线程或只有一个?
What I'm ultimately trying to achieve is this: I have a GMap, and want to have a few markers on it. 我最终想要达到的目标是:我有一个GMap,并希望在其上有一些标记。 These markers represent trains. 这些标记代表火车。 The marker pops up on the GMap at a certain point in time, and dissappears when it reaches it's destination. 标记在某个时间点弹出GMap,并在到达目的地时消失。 All the trains move about at the same time on the map. 所有火车在地图上同时移动。
If I need to post more of the code I tried please let me know. 如果我需要发布更多我试过的代码,请告诉我。 Thanks in advance! 提前致谢!
What you're looking for is Parallel.ForEach
: 您正在寻找的是Parallel.ForEach
:
Executes a foreach operation on an IEnumerable in which iterations may run in parallel. 在IEnumerable上执行foreach操作,其中迭代可以并行运行。
And you use it like this: 你这样使用它:
Parallel.ForEach(ObjectList, (obj) =>
{
// Do parallel work here on each object
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.