Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Got "Index out of bounds" Error on List.Add() in c# Parallel.ForEach

Tags:

c#

.net

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?

like image 660
Eric Yin Avatar asked Aug 15 '12 22:08

Eric Yin


People also ask

What is list index out of bounds (- 1?

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.

Why is my index out of bounds?

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.

How do I fix list index out of bounds 0 in Salesforce?

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.


1 Answers

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.

like image 115
Saeed Amiri Avatar answered Oct 07 '22 08:10

Saeed Amiri