Here is a nice article describing thread safety of random numbers:Getting random numbers in a thread-safe way
But I'm stuck with the "RandomGen2" example:
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();
}
}
Why is the thread static field copied to local variable: Random inst = _local; ? Why not to simply use
if (_local == null)
....
return _local.Next()