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?
List index out of bounds (-1) This problem occurs when the application writes an invalid value for the total number of sheets to the INI file during shut down.
The index out of bounds means you have tried to get something from an array or list with an invalid index. The -1 is most likely the index you gave it. An array or list will never have an index of -1 be valid.
ListException: List index out of bounds: 0' error occurs and how to resolve it. If we attempt to access an element at row 0, The code will throw an error if no data exist at row 0. It is a good practice to check whether there are records in the list before accessing any element from that list.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With