Here is the culmination of a Skeet posting for a random provider:
public static class RandomProvider
{
private static int seed = Environment.TickCount;
private static ThreadLocal<Random> randomWrapper = new ThreadLocal<Random>(() =>
new Random(Interlocked.Increment(ref seed))
);
public static Random GetThreadRandom()
{
return randomWrapper.Value;
}
}
I would like to use the same concept in a .NET 3.5 project, so ThreadLocal is not an option.
How would you modify the code to have a thread safe random provider without the help of ThreadLocal?
UPDATE
Ok, am going with Simon’s [ThreadStatic] for now since I understand it the best. Lots of good info here to review and rethink as time allows. Thanks all!
public static class RandomProvider
{
private static int _seed = Environment.TickCount;
[ThreadStatic]
private static Random _random;
/// <summary>
/// Gets the thread safe random.
/// </summary>
/// <returns></returns>
public static Random GetThreadRandom() { return _random ?? (_random = new Random(Interlocked.Increment(ref _seed))); }
}
You can use the ThreadStaticAttribute