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 | |
|---|---|---|
|
Next() | Returns a nonnegative random number. |
|
Next(Int32) | Returns a nonnegative random number less than the specified maximum. |
|
Next(Int32, Int32) | Returns a random number within a specified range. |
- 11/12/2009
- MacroLab
- 4/8/2009
- mattflaschen
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
- 3/9/2008
- Connected2010
- 3/11/2009
- Murat Markaryan