This question came up on an internal list recently… Thought I’d share it with you…

 

Q: We have created a System.Random object and shared it among multithreads.  After calling m_random.Next() for awhile (eg. 1 day), it stops generate any random but only return zero. I realize that random is not thread safe.  I interpreted it as it might return the same random (in race condition) not that it will only return zero after sometime.

 

A: This comes up now and then.  As you note, and as we say in the docs, the class is not threadsafe.  That means anything can happen.  In this case it looks like the seed is getting corrupted.  Consider this fix:

 

class ThreadSafeRandom

{

    private static Random random = new Random();

 

    public static int Next()

    {

       lock (random)

       {

           return random.Next();

       }

    }

}

 

Also, if you are using this for any kind of security\privacy purposes, we suggest using the Random number generator in the System.Security namespace: RandomNumberGenerator.