TerribleDog
TerribleDog

Reputation: 1247

While loop or For loop does not exit

I am trying to create a thread and add it in a list of Threads:

int j = 0;
while(j!=6)
    {
        Thread th = new Thread(() => SaveImages(L104List[j], folderFilePath, bw));
        ThreadList.Add(th);
        j++;
        //th.Start();
     }

but it is not exiting when j becomes 6. So it throws a s exception:

Additional information: Index was out of range. Must be non-negative and less than the size of the collection.

BUT, whenever I try to use breakpoints to manually iterate the loop, it exits and goes to the next statements of code. Why is it doing that?

PS. I also tried for loop, and it also does that.

Upvotes: 0

Views: 229

Answers (2)

TheGeneral
TheGeneral

Reputation: 81473

  • To start with you will have a Capture problem with your Closure.

  • Your while loops seems like the perfect case for a for or foreach loop

  • I am yet to be satisfied that you need to use the Thread class for this, or that it will be optimal if you do. Why not use Task instead.

  • Taking this a step further why not let TPL do the hard work for you

Example of easy parallelism

Parallel.ForEach(L104List, (item) => SaveImages(item, folderFilePath, bw));

The advantages are

  • You won't have a closing of the loop variable problem
  • You don't have to worry about inefficient thread switching when you overload your cpus
  • The task scheduler will divvy out threads from the threadpool in a way that is most likely more efficient than running as many threads as your array holds.
  • It will wait until all your work is done
  • It's one line of code and easier to understand

Additional notes, if you can make your method async, you can probably gain even more efficiency.


Parallel.ForEach Method

Executes a foreach (For Each in Visual Basic) operation in which iterations may run in parallel.

Upvotes: 3

Gauravsa
Gauravsa

Reputation: 6514

I will do something like this:

foreach(var data in L104List)
{
   string local = data;
   ThreadStart work = delegate { SaveImages(local, folderFilePath, bw); };
   new Thread(work).Start();
}

Upvotes: 1

Related Questions