Incorrect number of items in List populated in Parallel.For loop

262 views Asked by At

I'm trying to populate a list with a million independently generated items. But after the loop I'm getting less items: 999960, 998534 etc.

As a bypass I've wrapped this code in another that checks generated amount and generates missing items.

I've also tried to sleep after the loop, but it doesn't give a result closer to desired.

var someList = new List<ListItem>();
Parallel.For(0, 1000000, _ =>
{
    var item = new ListItem();

    //some logic here

    someList.Add(item);
});

System.Console.WriteLine(someList.Count()); // returns less than 1000000

What is the reason of such behaviour and what is the proper way to solve this task?

2

There are 2 answers

3
jmcilhinney On BEST ANSWER

The List<T> is not thread-safe. You can use a ConcurrentBag<T>, although that is an ICollection<T>, not an IList<T>. If you need the latter then you will have to synchronise the multiple threads, probably using a lock statement.

1
JonasH On

If you know how many items you will generate, just use an array:

var someList = new ListItem[1000000];
Parallel.For(0, someList.Length, i =>
{
    var item = new ListItem();

    //some logic here

    someList[i] = item;
});