Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Random keeps on returning the same value

Tags:

.net

random

I am using a System.Random object which is instantiated with a fixed seed all thoughout the application. I am calling the NextDouble method and after some time passed I am getting 0.0 as result.

Is there any remedy to this, has anyone else encountered this ?

EDIT: I have one seed for the whole run which is set to 1000 for convience sake. The random.NextDouble is called several hundred thousand times. It is an optimizer application and could run for couple hours, but this actually happens after 10-0 mins of execution. I have recently added little bit more random calls to the app.

like image 248
Tomas Pajonk Avatar asked Nov 17 '08 15:11

Tomas Pajonk


1 Answers

The random number generator in .NET is not thread safe. Other developers have noticed the same behaviour, and one solution is as follows (from http://blogs.msdn.com/brada/archive/2003/08/14/50226.aspx):

class ThreadSafeRandom
{
    private static Random random = new Random();

    public static int Next()
    {
       lock (random)
       {
           return random.Next();
       }
    }
}
like image 59
e.James Avatar answered Sep 23 '22 22:09

e.James