Thursday 25 March 2010

Random.Next() Method

Random.Next(int minValue, int maxValue), return value is a psuedo-random number greater than or equal to minValue and less than maxValue. If minValue and maxValue are equal, this value is returned.

Thread Safety

Random's instance methods are not thread-safe. That's why the class (and almost every class in the .Net framework) says, "Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe." Some people just don't know how to read documentation.

Warning: Random.Next() NOT thread safe; results in constant 0

Warning: Random.Next() NOT thread safe; results in constant value equal to the minimum specified value (Next(int)) or 0 if uing the parameterless overload (Next()). Calling Random.Next() from multiple threads will eventually result in a corrupted class and a constant random number of minvalue.

Instantiating random numbers with the default constructor can result in identical random number sequences, as the feed is based on the current datatime. This can lead to unexpected results.

A suggested procedure is:

static class RandomFactory
{

private static Random globalRandom = new Random();


public static Random Create() {

lock (globalRandom) {

Random newRandom = new Random(globalRandom.Next());

return newRandom;

}

}

Instantiate your random object through RandomFactory.Create(). This will always lead to unique randomizers within each procedure and minimizes the number of lockin required.

No comments:

Post a Comment