Random giving the same value after too many usages

Dec 1 2009 10:54 AM
Hello I'm coding on a simulator at the moment, what it is simulating is not very important. Each simulation returns a number in the 7000-10000 range, depending on certain random events. The simulation is run several thousand times to get a good average value.

The problem: after running around 1000 to 4500 simulations (it varies), all new random numbers are zero which makes all the following simulations identical. The current implementation looks like this:

in class Simulation:

public static Random Random = new Random();
.....
public double getRandom()
{
double random = Random.NextDouble();
Console.Write(String.Format("{0:0.00} ", random));
return random;
}

The getRandom method is called around 500 times per simulation, and several thousand simulations are run in 2 threads working in parallel. This problem didn't exist before i introduced multithreading in the program and I'm frankly stumped of how it can appear since Random is supposed to be thread safe when used as a static.

Any help would be greatly appreciated.

Answers (6)