Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
.NET Framework 3.5
System Namespace
Random Class
Random Methods
Next Method
Collapse All/Expand All Collapse All
Members FilterMembers Filter
Frameworks FilterFrameworks Filter
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
.NET Framework Class Library
Random..::.Next Method

Returns a random number.

  NameDescription
Public methodSupported by the .NET Compact FrameworkSupported by the XNA FrameworkNext()()()Returns a nonnegative random number.
Public methodSupported by the .NET Compact FrameworkSupported by the XNA FrameworkNext(Int32)Returns a nonnegative random number less than the specified maximum.
Public methodSupported by the .NET Compact FrameworkSupported by the XNA FrameworkNext(Int32, Int32)Returns a random number within a specified range.
Top
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Warning: Random.Next() NOT thread safe; results in constant 0      Martijn Kaag ... Murat Markaryan   |   Edit   |   Show History

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

Thread-safety      mattflaschen   |   Edit   |   Show History
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.
Tags What's this?: Add a tag
Flag as ContentBug
Return Value      MacroLab   |   Edit   |   Show History
In the case of 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.
Tags What's this?: Add a tag
Flag as ContentBug
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement
Page view tracker