Random number generator only generating one random number Random number generator only generating one random number

To generate a random number it involves instantiating the Random class then calling the Next function with a minimum and maximum value as follows: new Random().Next(min, max) so why is it always returning the same number? This commonly occurs when this is being called in a loop.


Here is an example function that generates a random number with how it is being called in a loop:


public static int RandomNumber(int min, int max)
{
    Random random = new Random();
    return random.Next(min, max);
}
for (var i = 0; i < 5; i++) {
	var randomNumber = RandomNumber(0, i);
	// Do something with the number
}

Now because the call to the random number generator is in a loop that executes in milliseconds, when the RandomNumber class is instantiated it is seed with the current date time. Inside the loop this happens so fast that it is always the same seed causing the same number generated each time.

Avoiding duplicate Random Numbers

Let's alter the existing code to maintain a static reference to the Random class so that when we call Next it is smart enough to not generate the same number on the first call:


private static Random random = new Random();
public static int RandomNumber(int min, int max)
{
    return random.Next(min, max);
}
for (var i = 0; i < 5; i++) {
	var randomNumber = RandomNumber(0, i);
	// Do something with the number
}

If this code has a chance of being called concurrently it might be a good idea to include a lock on the function so it prevents calling Next at the exact millisecond because we are accessing a static object:


private static Random random = new Random();
private static object randomLock = new object();
public static int RandomNumber(int min, int max)
{
	lock (randomLock) {
		return random.Next(min, max);
	}
}
for (var i = 0; i < 5; i++) {
	var randomNumber = RandomNumber(0, i);
	// Do something with the number
}

With the lock (randomLock) any concurrent calls will have a slight wait before executing the call until the lock has been release on the randomLock object.

Published on Mar 3, 2020

Tags: ASP.NET MVC and Web API Tutorial | c#

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.