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?
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.