Threading.Task.Parallel.For中的C#Bug?

Ada*_*ght -3 c# parallel-processing task-parallel-library

Parallel.For中有这个错误吗?

   public class DataPoint
        {
            public int Game { get; set; }
            public byte Card { get; set; }
            public byte Location { get; set; }
            public DataPoint(int g,byte c,byte Loc)
            {
                Game = g;
                Card = c;
                Location = Loc;
            }
            public override string ToString()
            {
                return String.Format("{0} {1} {2}",Game,Card,Location);
            }
        }
Run Code Online (Sandbox Code Playgroud)

它必须是Parallel.For中的错误

private static System.Collections.Concurrent.ConcurrentBag<DataPoint> FillData()
    {
        var points = new System.Collections.Concurrent.ConcurrentBag<DataPoint>();
        long c = 32768;
        long z = 0;
        Parallel.For(z, c, (i) =>
        {
            points.Add(new DataPoint( rand.Next(1, 100001),
                                      (byte)rand.Next(1, 144),
                                      (byte)rand.Next(1, 40)));
            });
        return points;
    }
Run Code Online (Sandbox Code Playgroud)

作品

private static System.Collections.Concurrent.ConcurrentBag<DataPoint> FillData()
    {
        var points = new System.Collections.Concurrent.ConcurrentBag<DataPoint>();
        long c = 32769;
        long z = 0;
        Parallel.For(z, c, (i) =>
        {
            points.Add(new DataPoint( rand.Next(1, 100001),
                                      (byte)rand.Next(1, 144),
                                      (byte)rand.Next(1, 40)));
            });
        return points;
    }
Run Code Online (Sandbox Code Playgroud)

不会默认为{1,1,1}

Hen*_*man 7

Random类被明确记录为不是线程安全的.

您错误地在错误的地方+时间使用错误的班级.

库中没有错误.

编辑

这里的简短解决方案是,Random()并且Parallel.For()不能很好地结合在一起.只需用正常for(;;)循环替换Parallel.For即可.对于32k元素,您不会注意到差异.

如果你仍然需要它并行,你将不得不拆分范围,运行几个任务并给每个任务它自己的Random实例.

  • 我向你们保证,*库中有一个*.只是这不是它. (10认同)
  • @Eric:只要它只是那个,我想我们可以忍受. (2认同)

Dan*_*ite 6

Randoms在多线程情况下永远不会好.

阅读:http://msdn.microsoft.com/en-us/library/system.random.aspx

  • @Adam:你问过TPL中是否有错误.答案是:否.如果您想要更具建设性的答案,请提出更好的问题.很抱歉接受你,但要考虑Q + A的工作原理. (5认同)