Sweeper
Sweeper

Reputation: 271645

How to create 2 Random objects in 2 consecutive lines of code with different seeds?

I want to make 2 different Random objects in 2 consecutive lines of code. The parameterless constructer of the Random class is like this:

public Random() 
    : this(Environment.TickCount) {
  }

It uses Environment.TickCount as the seed. TickCount represents the amount of time that has passed since the OS is switched on, right?

I tried the following:

Random r1 = new Random ();
Random r2 = new Random ();

And I found out that the 2 Random objects had the same seed because their Next methods return the same number each time. I was surprised by how fast a line of code can be executed. Then I tried:

long tick1 = Environment.TickCount;
for (int i = 0 ; i < 100000 ; i++) {

}
long tick2 = Environment.TickCount;
Console.WriteLine (tick2 - tick1);

And I get 0. So I iterated 100000 times and still, not even 1 millisecond has passed?

I just want to ask how can I create 2 different Random objects or is there another way to generate random numbers?

Upvotes: 0

Views: 140

Answers (2)

Ramin Bateni
Ramin Bateni

Reputation: 17415

Base on @PankajMishra's answer, try this one:

//Function to get random number
private static readonly Random getrandom = new Random();
private static readonly object syncLock = new object();
public static int GetRandomNumber(int min, int max)
{
    lock(syncLock) { // synchronize
        return getrandom.Next(min, max);
    }
}

lock block is effective when you use it in a multi-threading program, if you sure just one thread use it, so you can prevent lock to increase your code performance.

Upvotes: 2

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

To me, it seems like an XY problem, because you don't need two separate Random instances - you can use the same one to generate all your random number, can't you? Just call Next again and that's it:

var rnd = new Random();
int firstRandomInt = rnd.Next();
int secondRandomInt = rnd.Next();

However, you really need 2 Random instances, you can use the first one to seed the second one:

var rnd = new Random();
var rnd2 = new Random(rnd.Next());

Upvotes: 2

Related Questions