mardi 23 août 2016

C# Generate random numbers, while using library, that use internal Random instance

In order to ensure different random numbers, you should use just one instance of a Random class, as suggested in the answers here, here and here.

In my library, I need the random numbers, so I created a class Randomizer, which provides methods, that returns random numbers using single Random instance. Here is a fragment of the Randomizer code:

class Randomizer
{
    private Randomizer() { }
    public static Randomizer Instance { get; } = new Randomizer();

    private static readonly Random random = new Random();
    private static readonly object syncLock = new object();

    public int Next(int minValue, int maxValue)
    {
        lock(syncLock)
        {
            return random.Next(minValue, maxValue);
        }
    }

    // rest of code
}

Now, what if a user of my library also need the random numbers? Should I make my Randomizer class public and specify in the documentation of the library, that users should use my Randomizer class in order to generate random numbers?




Aucun commentaire:

Enregistrer un commentaire