With 1 thread, execute multiple methods at the same time
So, I have a list with over 900 positions in C #. For each entry in the list, a method must be executed, although they must go simultaneously. At first I thought about this:
public void InitializeThread()
{
Thread myThread = new Thread(run());
myThread.Start();
}
public void run()
{
foreach(Object o in ObjectList)
{
othermethod();
}
}
The problem now is that this will execute one method for each item in the list. But I want each of them to work at the same time.
Then I tried to make a separate stream for each entry, like:
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 be giving me system.outofmemory (not suprise) exceptions since the list has almost 1000 entries. Is there a way to successfully run all these methods at the same time? Or use multiple threads or just one?
Ultimately I'm trying to achieve this: I have a GMap and want to have multiple markers. These markers represent trains. The marker appears on the GMap at a certain point in time and disappears when it reaches the target. All trains move simultaneously on the map.
If I need to post more code I've tried, let me know. Thanks in advance!
source to share
What you are looking for is Parallel.ForEach
:
Performs a foreach operation on an IEnumerable in which iterations can be performed in parallel.
And you use it like this:
Parallel.ForEach(ObjectList, (obj) =>
{
// Do parallel work here on each object
});
source to share