In the following code, it seems that only every other element of the array is populated. Why?
Random rand = new Random();
int byteLength = 10000000;
var result = new byte[10][];
Parallel.For(0, 10, (i) =>
{
int length = rand.Next(byteLength);
var tempResult = new byte[length];
Thread.Sleep(100);
rand.NextBytes(tempResult);
result[i] = tempResult;
});
Contrast with this (non-parallel) code that fills each element:
rand = new Random();
var result2 = new byte[10][];
for (int i = 0; i < 10; i++)
{
int length = rand.Next(byteLength);
var tempResult = new byte[length];
Thread.Sleep(100);
rand.NextBytes(tempResult);
result2[i] = tempResult;
}
Comparing with the examples in the documents on MSDN, I suspect that this is because it resultis located outside the delegate Parallel.For- thus, streams occur when accessing result. But, as a newbie to multithreading, I'm not sure if that is the case.
source
share