1

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?

Mohammed Nafie
  • 151
  • 1
  • 10

1 Answers1

1

You need to introduce local variable like this.

public void InitializePorts(int numOfPortThreads)
        {
            Thread[] tPortArr = new Thread[numOfPortThreads];

            for (int i = 0; i < numOfPortThreads; i++)
            {
                int j = i;
                tPortArr[j] = new Thread( () => new PortSim().PortRun(j));
                tPortArr[j].Start();
            }
        }

you may be wondering why just google closures in c#

ClearLogic
  • 3,616
  • 1
  • 23
  • 31
  • 1
    Side note: if you are not planning to make answer better than many duplicates you should just vote to close instead... – Alexei Levenkov Aug 03 '17 at 00:24
  • 1
    I was still googling and found out this article online: https://www.martyndavis.com/?p=405. It explained it in details. Thanks for your answer though. I really needed to know why this is happening. – Mohammed Nafie Aug 03 '17 at 00:36