How do I run thread-safe random numbers in async actions?
It always return zero. I tried to to make a instance in startup.cs which set a static istance of the current but it still always return zero.
I am using ASP.Net Core.
public class SafeRandom
{
public static SafeRandom Instance { get; private set; }
public SafeRandom()
{
Instance = this;
}
private readonly static Random _global = new Random();
[ThreadStatic]
private Random _local;
public int Next(int min,int max)
{
Random inst = _local;
if (inst == null)
{
int seed;
lock (_global) seed = _global.Next();
_local = inst = new Random(seed);
}
return inst.Next(min,max);
}
}
Aucun commentaire:
Enregistrer un commentaire