在下面的代码中,似乎只有数组的每个其他元素都被填充.为什么?
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; });
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; }
与MSDN文档中的the examples相比,我怀疑这是因为结果在Parallel.For委托之外 – 因此,线程在访问结果时遇到问题.但作为多线程的新手,我不确定是这种情况.