I have a loop in my code
Parallel.For(0, Cnts.MosqPopulation, i => { DoWork() });
however in the DoWork()
function, there a
I would consider something like this:
private static int _tracker = 0;
private static ThreadLocal _random = new ThreadLocal(() => {
var seed = (int)(Environment.TickCount & 0xFFFFFF00 | (byte)(Interlocked.Increment(ref _tracker) % 255));
var random = new Random(seed);
return random;
});
I'm not a huge fan of ThreadStatic
these days. We have better tools than that using ThreadLocal
. Just use _random.Value
in your parallel loop and it will give you a new Random
per thread.
It combines an atomically incrementing value as well as the default behavior of using Environemnt.TickCount
. The incrementing value is there to solve the problem of two Random's getting the same seed. Note that this approach only allows 255 randoms to be created. If you need more, then change the size of the mask.
As you already noted, this isn't usable for secure purposes.