Parallel.For List <Int32>

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,以及数组的下限.

任何人都知道为什么?

Dus*_*vis 5

您正在使用不是线程安全的List <>.使用ConcurrentBag <>.我一直遇到这种情况,同时切换到并行循环.它会间歇性地发生,而不是每次都发生,所以很难检测到.

  • `Random`也不是线程安全的,所以如果在切换到'ConcurrentBag <>`后继续失败,不要感到惊讶. (3认同)
  • 这将比普通的顺序代码慢得多. (2认同)
  • @SLaks我同意但这不是他的问题.他的问题是他为什么会看到错误,并且在处理需要它的任务的并行循环时会为其他有类似问题的人提供有价值的信息. (2认同)