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

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

Problem Description:

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?

Solution – 1

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.

Solution – 2

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;
});
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject