Random.Next() always returns 0

Viewed 6549

I am using a single Random instance to rapidly get random numbers in a Parallel query, but I have noticed that, eventually, Random.Next always returns zero. Is there a reason for that?

2 Answers

Random isn't thread-safe. You should use a different instance of Random for each thread, instead. I wouldn't suggest locking as you've suggested, as otherwise if that's a significant part of your overall time, it could end up being no faster than running it in a single thread to start with. Instead, you can use a thread local variable to have a separate instance per thread - taking care to ensure that you don't accidentally use the same seed for all the instances, which would give you the same sequence of of numbers in each thread.

See my article on randomness for more details, including sample code.

Random apparently doesn't like being used in several threads at once. Putting a lock around the call like this:

object syncLock = new object();
<snip>
int value;
lock(syncLock){
    value = random.Next();
}

seems to have solved the problem.

Related