RANDOM NUMBER GENERATOR ONLY GENERATING ONE RANDOM NUMBER

Goti Bandu

Total Post:119

Points:835
Posted by  Goti Bandu
C# 
C#
 835  View(s)
Ratings:
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. 

  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: Random number generator only generating one random number

    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);
        }
    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!