I'm having trouble with the Random class in .NET, I'm implementing a threaded collection which is working fine, except for one smaller detail. The collection is a Skip list and those of you familiar with it know that for every node inserted I need to generate a new height that is <= CurrentMaxHeight+1
, here's the code that I'm using to do that (I know it's very inefficient, but it works and thats my main priority now)
int randomLevel()
{
int height = 1;
while(rnd.NextDouble() >= 0.5 && height < MaxHeight)
++height;
return height;
}
My problem here is that sometimes I keep getting only 1 back from this for several thousand elements in a row which kills the performance of the skip list. The chance for 10.000 elements to generate only 1 from this method in a row, seems very slim (happens pretty consistently).
So I'm assuming (guessing) that there is a problem with the Random
object in some way, but I don't really know where to start digging around. So I turn to stackoverflow to see if anyone has an idea?
Edit
The rnd-variable is declared in the class SkipList<T>
, and it is accessed from several threads (each thread calls .Add on the collection and Add calls .randomLevel)