Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel.For List<Int32>

I wrote the following lines of code:

    private static List<Int32> GetRandomList_Serial()
    {
        List<Int32> returnValue = new List<int>();
        Random random = new Random();

        for (int i = 0; i < 10000000; i++)
        {
            returnValue.Add(random.Next());
        }
        returnValue.Sort();
        return returnValue;
    }

I then wrote this block of code:

    private static List<Int32> GetRandomList_Parallel()
    {
        List<Int32> returnValue = new List<int>();
        Random random = new Random();

        Parallel.For(0, 10000000, y =>
        {
            returnValue.Add(random.Next());
        });

        returnValue.Sort();
        return returnValue;

    }

Serial works fine, Parallel throws this exception:

System.ArgumentException was unhandled by user code

Destination array was not long enough. Check destIndex and length, and the array's lower bounds.

Anyone have an idea why?

like image 726
James Dixon Avatar asked Dec 27 '25 16:12

James Dixon


1 Answers

You're using a List<> which is not thread safe. Use ConcurrentBag<>. I run into this all the time while switching to Parallel loops. It will happen intermittently, not every time so it's hard to detect.

like image 81
Dustin Davis Avatar answered Dec 31 '25 17:12

Dustin Davis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!