Jam*_*xon 3 .net task-parallel-library
我写了以下几行代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
然后我写了这段代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
串口工作正常,并行抛出此异常:
System.ArgumentException未被用户代码处理
目标数组不够长.检查destIndex和length,以及数组的下限.
任何人都知道为什么?
您正在使用不是线程安全的List <>.使用ConcurrentBag <>.我一直遇到这种情况,同时切换到并行循环.它会间歇性地发生,而不是每次都发生,所以很难检测到.
| 归档时间: |
|
| 查看次数: |
385 次 |
| 最近记录: |