隨機提供商這裏是一個Skeet posting for a random provider的高潮:實現在.net 3.5
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;
}
}
我想用同樣的概念在.NET 3.5的項目,這樣的ThreadLocal是不是一種選擇。
你會如何修改代碼以有沒有的ThreadLocal的幫助下,線程安全的隨機提供商?
UPDATE
好吧,我與西蒙的[ThreadStatic]打算現在,因爲我的理解是最好的。有很多很好的信息可以在時間允許的情況下回顧和重新思考。謝謝大家!
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))); }
}
還有一個後續up article:https://msmvps.com/blogs/jon_skeet/archive/2009/11/04/revisiting-randomness.aspx他討論了其他線程安全策略。 – CodesInChaos 2012-03-16 17:57:56