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}
Random类被明确记录为不是线程安全的.
您错误地在错误的地方+时间使用错误的班级.
库中没有错误.
这里的简短解决方案是,Random()并且Parallel.For()不能很好地结合在一起.只需用正常for(;;)循环替换Parallel.For即可.对于32k元素,您不会注意到差异.
如果你仍然需要它并行,你将不得不拆分范围,运行几个任务并给每个任务它自己的Random实例.
Randoms在多线程情况下永远不会好.
阅读:http://msdn.microsoft.com/en-us/library/system.random.aspx