-2

I'm trying to figure out why is this error showing, but I can't. I think that everything's okay, but at some point the value "i" at readTest is == 2. Which is not supposed to... listW has 2 objects, and the "i" should only be 0 and 1. I don't where the 2 is coming from. Am I making anything wrong? I've done some testing and the i=2 only happens at readTest. What's happening?

Thank you for your attention guys

public void readTest(int i)
        {
            for (int j = 0; j != leftListList[i].getKeyValues().Length; j++)
            {
                string read = ws.Read(listW[i], wi[i].GetKey(), leftListList[i].getKeyValues()[j]);
                WsRead wsRead = wi[i].BuildRead(read, leftListList[i].getKeyValues()[j]);
                readList.Add(wsRead);

                Console.WriteLine("READ: " + leftListList[i].getKeyValues()[j]);
            }
        }

        public void threadTest()
        {
            for (int i = 0; i != listW.Length; i++)
            {
                    Thread t = new Thread(() => readTest(i));
                    t.Start();
                }
            }

1 Answers1

1

Introduce a local variable, say index:

for (int i = 0; i < listW.Length; i++) // i < listW.Length is more readable
{
    int index = i;
    ...
    else 
    {
        // now each thread has its own index
        Thread t = new Thread(() => readTest(index));
        t.Start();
    }
}

when Thread finally starts (it takes time to create a new thread), the loop is completed and thus i == 2

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215