Reputation: 1247
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
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
Additional notes, if you can make your method async, you can probably gain even more efficiency.
Executes a foreach (For Each in Visual Basic) operation in which iterations may run in parallel.
Upvotes: 3
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