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?
In order to prevent the issue, instead of List you may use
ConcurrentQueueor similar Concurrent collections in your parallel part. Once the parallel task is done, you can put it in theList<T>.For more information take a look at System.Collections.Concurrent namespace to find the suitable collection for your use case.