Home > DeveloperSection > Forums > Random number generator only generating one random number
Goti Bandu

Total Post:119

Points:835
Posted on    May-29-2013 1:56 AM

 C# C# 
Ratings:


 1 Reply(s)
 601  View(s)
Rate this:
Hi,

I have the following function:

//Function to get random number
public static int RandomNumber(int min, int max)
{
    Random random = new Random();
    return random.Next(min, max);
}

I'm trying as following

byte[] mac = new byte[6];
for (int x = 0; x < 6; ++x)
    mac[x] = (byte)(Misc.RandomNumber((int)0xFFFF, (int)0xFFFFFF) % 256);

If I step that loop with the debugger during run time I get different values (which is what I want). However, if I put a break point two lines below that code, all members of the "mac" array have equal value.

Please resolve my problem.
Thanks in advance. 



AVADHESH PATEL

Total Post:604

Points:4228
Posted on    May-29-2013 9:01 AM

Hi Goti!

Every time you do new Random() it is initialized using the clock. This means that in a tight loop you get the same value lots of times. You should keep a single Random instance and keep using Next on the same instance.

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


Don't want to miss updates? Please click the below button!

Follow MindStick