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);
}
How I call it:
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 runtime I get different values (which is what I want).
However, if I put a breakpoint two lines below that code, all members of the mac array have equal value.
Why does that happen?
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.Edit (see comments): why do we need a
lockhere?Basically,
Nextis going to change the internal state of theRandominstance. If we do that at the same time from multiple threads, you could argue “we’ve just made the outcome even more random”, but what we are actually doing is potentially breaking the internal implementation, and we could also start getting the same numbers from different threads, which might be a problem – and might not. The guarantee of what happens internally is the bigger issue, though; sinceRandomdoes not make any guarantees of thread-safety. Thus there are two valid approaches:Randominstances per threadEither can be fine; but mutexing a single instance from multiple callers at the same time is just asking for trouble.
The
lockachieves the first (and simpler) of these approaches; however, another approach might be:this is then per-thread, so you don’t need to synchronize.