C# Random Numbers aren’t being “random”

My guess is that randomNumber creates a new instance of Random each time… which in turn creates a new pseudo-random number generator based on the current time… which doesn’t change as often as you might think.

Don’t do that. Use the same instance of Random repeatedly… but don’t “fix” it by creating a static Random variable. That won’t work well either in the long term, as Random isn’t thread-safe. It will all look fine in testing, then you’ll mysteriously get all zeroes back after you happen to get unlucky with concurrency 🙁

Fortunately it’s not too hard to get something working using thread-locals, particularly if you’re on .NET 4. You end up with a new instance of Random per thread.

I’ve written an article on this very topic which you may find useful, including this code:

using System;
using System.Threading;

public static class RandomProvider
{    
    private static int seed = Environment.TickCount;

    private static ThreadLocal<Random> randomWrapper = new ThreadLocal<Random>
        (() => new Random(Interlocked.Increment(ref seed)));

    public static Random GetThreadRandom()
    {
        return randomWrapper.Value;
    }
}

If you change your new Random() call to RandomProvider.GetThreadRandom() that will probably do everything you need (again, assuming .NET 4). That doesn’t address testability, but one step at a time…

Leave a Comment