Correct way to use Random in multithread application [duplicate]

I use something like this:

public static class StaticRandom
{
    static int seed = Environment.TickCount;

    static readonly ThreadLocal<Random> random =
        new ThreadLocal<Random>(() => new Random(Interlocked.Increment(ref seed)));

    public static int Rand()
    {
        return random.Value.Next();
    }
}

readonly ThreadLocal<Random> random = 
    new ThreadLocal<Random>(() => new Random(GetSeed()));

int Rand()
{
    return random.Value.Next();
}

static int GetSeed()
{
    return Environment.TickCount * Thread.CurrentThread.ManagedThreadId;
}

(shamelessly stolen from the comment of Jeroen Vannevel)


I think what you want is threadstatic

[ThreadStatic]
static Random rnd=new Random();

int Rand()
{
    if ( rnd == null ) 
    {
       rnd = new Random()
    }
    //Now each thread gets it's own version
    return rnd.Next();
}

That way each thread get their own version of your rnd property

The reason your locking will increase cpu usage is because all threads will wait on that single point (should only be an issue if you use it a lot)

[Update] i fixed the initialization. As someone pointed out it does leave the fact that if you start multiple threads in the same milisecond then they will produce the same results.