I am trying to pass more than one parameter to a thread.
I am only testing with one parameter though, and the Lambda Expression is not passing the valeis of the parameters correctly. The ParameterizedThreadStart is working correctly, but I can only pass one object variable and not more and this limits me.
I have made an example for each and the outputs of the Lambda Expression method outputs are incorrect.
For both cases, numOfPortThreads = 2
Using ParameterizedThreadStart
public void InitializePorts(int numOfPortThreads)
{
Thread[] tPortArr = new Thread[numOfPortThreads];
for (int i = 0; i < numOfPortThreads; i++)
{
tPortArr[i] = new Thread(new ParameterizedThreadStart(new PortSim().PortRun));
tPortArr[i].Start(i);
}
}
In "PortSim.cs"
public void PortRun(object portID)
{
portStopWatch.Start();
Console.WriteLine("This is Port {0}", portID);
Console.ReadKey();
}
The output in that case is:
This is Port 0
This is Port 1
However, using Lambda Expression,
public void InitializePorts(int numOfPortThreads)
{
Thread[] tPortArr = new Thread[numOfPortThreads];
for (int i = 0; i < numOfPortThreads; i++)
{
tPortArr[i] = new Thread( () => new PortSim().PortRun(i));
tPortArr[i].Start();
}
}
In "PortSim.cs"
public void PortRun(int portID)
{
portStopWatch.Start();
Console.WriteLine("This is Port {0}", portID);
Console.ReadKey();
}
The output in that case is:
This is Port 2
This is Port 2
What is wrong with the second example? Why does it yield incorrect results?