Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Creating multiple threads using Lambda

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?

like image 891
Maximiliaan Aelvoet Avatar asked Dec 29 '25 21:12

Maximiliaan Aelvoet


1 Answers

The problem is the way i is captured in the lambda. Make a local copy inside the loop to have each lambda capture a distinct value:

public void GatherDataFromSwitches(Device[] switches)
{      
    List<Thread> workerThreads = new List<Thread>();
    for(int i = 0; i < switches.Length ; i++)
    {
        int j = i; // local i
        Thread t = new Thread(unused => GatherDataFromSwitch(switches[j]));
        workerThreads.Add(t);
        t.Start();
    }
    foreach (Thread d in workerThreads) d.Join(); //wait for all threads to finish
}

Or pass i explicitly as a parameter to the thread:

public void GatherDataFromSwitches(Device[] switches)
{      
    List<Thread> workerThreads = new List<Thread>();
    for(int i = 0; i < switches.Length ; i++)
    {
        Thread t = new Thread(param => { j = (int)param; GatherDataFromSwitch(switches[j]); });
        workerThreads.Add(t);
        t.Start(i);
    }
    foreach (Thread d in workerThreads) d.Join(); //wait for all threads to finish
}
like image 115
Tudor Avatar answered Dec 31 '25 09:12

Tudor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!