6 out of 7 rated this helpful - Rate this topic

Random.Next Method

Returns a random number.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

  Name Description
Public method Supported by the .NET Compact Framework Supported by the XNA Framework Next() Returns a nonnegative random number.
Public method Supported by the .NET Compact Framework Supported by the XNA Framework Next(Int32) Returns a nonnegative random number less than the specified maximum.
Public method Supported by the .NET Compact Framework Supported by the XNA Framework Next(Int32, Int32) Returns a random number within a specified range.
Top
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Thread-safety
No, 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.

Kind regards,

Martijn Kaag