Trying to find and understand the best approach to implement a thread-safe number generator in .NET Core 2.x or higher
First Iv'e found this - https://web.archive.org/web/20160326010328/http://blogs.msdn.com/b/pfxteam/archive/2009/02/19/9434171.aspx
After reading through it seems to me like there are couple of "good" ways -
- ThreadStatic Random instance, with a global random instance to generate seeds
- ThreadStatic Random instance, with a global RNGCryptoServiceProvider to generate seeds
Where basically you choose the latter if a strong cryptographically random is a requirement.
After some additional research I found out that since .NET Core 2.x System.Random class was revised, therefore the default seed generation which is no longer primary dependent on the system timer. (https://blogs.siliconorchid.com/post/coding-inspiration/randomness-in-dotnet)
Question - How does this affect the implementation of a thread-safe random class?
Refrencing the first link Iv'e shared code solution -
public static class RandomGen2
{
    private static Random _global = new Random();
    [ThreadStatic]
    private static Random _local;
    public static int Next()
    {
        Random inst = _local;
        if (inst == null)
        {
            int seed;
            lock (_global) seed = _global.Next();
            _local = inst = new Random(seed);
        }
        return inst.Next();
    }
}
Since dotnet core 2.x adjustments is a global locked seed generator even required? or a basic ThreadStatic random instance is all thats needed? such as -
    public static class ThreadSafeRandom
    {
        [ThreadStatic]
        private static Random _local;
        public static int Next()
        {
            Random inst = _local;
            if (inst == null)
            {
                _local = inst = new Random();
            }
            return inst.Next();
        }
    }
 
     
    