0

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.

3
  • I guess L104List might be less than 6 item in the collection. Commented Jan 31, 2019 at 3:44
  • @D-Shih it has a count of 6, so if the j gives 6, it throws and exception because the 6th in the array is 5 as number right? Commented Jan 31, 2019 at 3:45
  • Why not would you use L104List.Lenght > j be the condition? Commented Jan 31, 2019 at 3:47

2 Answers 2

3
  • 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.

Sign up to request clarification or add additional context in comments.

1 Comment

@TerribleDog You dont, everything will have finished after the execution of the Parallel.ForEach
1

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();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.