2

I am using a random number generator in my application. However, sometimes it hapeens to return exactly same value. My research shows that default Random constructor takes system time as seed. When same seed is used, same numbers are generated. So, if calling of my method is done in same system time (eg. with very little delay between calls) same numbers are generated.

So solution which looks good is to delay calls a little bit, so unique time is taken. My question is - what is atomic time unit in .NET seed generator - smallest number i can use for waiting so unique time is recognized and unique seed is generated?

Also, is right way to delay just make thread sleep?

for example

int smallestTimeUnit = 20; Thread.Sleep(smallestTimeUnit); 

Or is system time seed generation not reliable and should i implement my own way of Seed generation?

Thank you.

1
  • 7
    that is so the wrong way to approach this; having a Random instance that you use sequentially is far preferred (i.e. rather than new Random() each time, you store an instance somewhere) Commented Nov 18, 2011 at 11:23

3 Answers 3

10

The solution is to reuse the same Random object and not create a new one every time.

Sign up to request clarification or add additional context in comments.

Comments

1

As already answered, creating a single instance of Random is probably the best way.

But when you do want separate instances, you can easily make sure the Seeds are different:

static int baseSeed = 0; var r = new Random(baseSeed++); // not thread-safe 

The seeds need to be different but not necessarily random. If you don't like to use 1,2,3,.. seeds then use a separate static Random instance to generate the seeds.

And when you use it from multiple Threads use Interlocked.Increment() to change the baseSeed, or lock() the static Random.

2 Comments

Why not new Random(baseSeed++ + DateTime.TickCount)? +1 Either way
@jgauffin - it would be enough and better to use the time one (int baseSeed = TickCount;). Using it each time just invites overflow issues.
0

If you are generatic the random numbers in a method called many times, you need to pass it a Random object as parameter; something like this:

var random = new Random(); for (var i=0; i<=1000; i++) { .... foo(par, random); .... } void foo(string somePar, Random rnd) { var val = rnd.next(); } 

Comments