C# Bug in Threading.Task.Parallel.For?
Is this bug in Parallel.Fo开发者_JS百科r?
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);
}
}
It must be a bug in 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;
}
works
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;
}
Doesn't Defaults each to {1,1,1}
The Random class is explicitly documented as not Thread-safe.
You are using the wrong class at the wrong place+time in the wrong way.
There is no bug in the library.
Edit
The short solution here is that Random()
and Parallel.For()
don't go together well. Just replace the Parallel.For with a normal for(;;)
loop. For 32k elements, you won't notice the difference.
If you still want it in parallel, you'll have to split the range, run a couple of Tasks and give each Task it's own Random instance.
Randoms are never good in multithreaded situations.
Read: http://msdn.microsoft.com/en-us/library/system.random.aspx
Here is an awesome blog post by a MSFT employee on different methods to handle generating random numbers within Parallel loops and their performance implications:
http://blogs.msdn.com/b/pfxteam/archive/2009/02/19/9434171.aspx
精彩评论