Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Randomnumber generation - automatic seed

Tags:

c#

.net

random

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.


2 Answers

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

like image 193
jgauffin Avatar answered Feb 25 '26 11:02

jgauffin


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.

like image 36
Henk Holterman Avatar answered Feb 25 '26 11:02

Henk Holterman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!