I have a loop in my code
Parallel.For(0, Cnts.MosqPopulation, i => { DoWork() });
however in the DoWork()
function, there a
Using the ThreadStatic
attribute and a custom getter, you will get a single Random
instance per thread. If this is not acceptable, use locks.
public static class Utils
{
[ThreadStatic]
private static Random __random;
public static Random Random => __random??(__random=new Random());
}
The ThreadStatic
attribute does not run the initializer on each thread so you are responsible for doing so in your accessor. Also think about your seed initializer, you can use something like
new Random((int) ((1+Thread.CurrentThread.ManagedThreadId) * DateTime.UtcNow.Ticks) )