0

So I have a service that instantiates an array of objects and then starts a new process for those objects. I wait for the instantiation and the new processes to start before getting some data from the objects in a another thread. For some reason I am getting out bounds index when trying to read the data. It seems to be trying to access an index that is 1 larger than what i define (trying to access Os[4] when the last index is Os[3]), hence being out of bounds? what could be causing this?

        lock (initlock)
        {
            for (threadNum = 0; threadNum < 4; threadNum++)
            {
                Os[threadNum] = new myO();
                Thread TOs[threadNum] = new Thread(new ThreadStart(Os[threadNum].ProcessData));
                TOs[threadNum].Start();
            }
        }

        lock (initlock)
        {
            for (int i = 0; i < 4; i++)
            {
                Thread rd[i] = new Thread(new ThreadStart(() => Os[i].GetData());
                rd[i].Start();
            }
        }
skevthedev
  • 447
  • 1
  • 7
  • 20

1 Answers1

4
for (int i = 0; i < 4; i++)
{
    int index = i;
    Thread rd[index] = new Thread(new ThreadStart(() => Os[index].GetData());
    rd[index].Start();
}

More in this answer.

Backs
  • 24,430
  • 5
  • 58
  • 85