Reputation: 8993
Here is the code
List<string> something = new List<string>();
Parallel.ForEach(anotherList, r =>
{
.. do some work
something.Add(somedata);
});
I get the Index out of bounds
error around 1 time per hundred run. Is there anyway to prevent the conflict (I assume) caused by threading?
Upvotes: 16
Views: 7397
Reputation: 22565
In order to prevent the issue, instead of List you may use ConcurrentQueue
or similar Concurrent collections in your parallel part. Once the parallel task is done, you can put it in the List<T>
.
For more information take a look at System.Collections.Concurrent namespace to find the suitable collection for your use case.
Upvotes: 23
Reputation: 571
I found that lock (yourObject)
also negates the threading problem
Upvotes: 1