public void GatherDataFromSwitches(Device[] switches)
{
List<Thread> workerThreads = new List<Thread>();
for(int i = 0; i < switches.Length - 1; i++)
{
Thread t = new Thread(unused => GatherDataFromSwitch(switches[i]));
workerThreads.Add(t);
t.Start();
}
foreach (Thread d in workerThreads) d.Join(); //wait for all threads to finish
}
If I loop through switches after having run that method I notice that somehow some switches had no added data, and some switches had data added from multiple switches. So something went wrong with passing the reference to the worker threads. I'm still not sure what exactly, but I solved the problem by adding
Thread.Sleep(100);
right after
t.Start();
I'm assuming this works because now the newly created thread has some time to initialize before the next is created. But this is a work around, not a fix. Is it because of how lambda expressions work?
How do I properly go around this?