我有以下代碼來緩存我在多線程應用程序中使用的並行字典中某些類的實例。在此ConcurrentDictionary緩存場景中鎖定必需
簡單地說,當我用id參數傳遞類時,它首先檢查具有給定標識的私有類的實例是否存在於字典中,如果不創建私有類的實例(這需要很長時間,的秒),並將其添加到字典供將來使用。
public class SomeClass
{
private static readonly ConcurrentDictionary<int, PrivateClass> SomeClasses =
new ConcurrentDictionary<int, PrivateClass>();
private readonly PrivateClass _privateClass;
public SomeClass(int cachedInstanceId)
{
if (!SomeClasses.TryGetValue(cachedInstanceId, out _privateClass))
{
_privateClass = new PrivateClass(); // This takes long time
SomeClasses.TryAdd(cachedInstanceId, _privateClass);
}
}
public int SomeCalculationResult()
{
return _privateClass.CalculateSomething();
}
private class PrivateClass
{
internal PrivateClass()
{
// this takes long time
}
internal int CalculateSomething()
{
// Calculates and returns something
}
}
}
我的問題是,我需要增加一個鎖周圍的外部類的構造函數的產生和分配部分以使此代碼線程安全的還是不錯的,因爲它是什麼?
更新:
後SLaks的suggestion,試圖用ConcurrentDictionary的GetOrAdd()法的Lazy的組合,但遺憾的是PrivateClass
的構造還是調用一次以上。測試代碼見https://gist.github.com/3500955。
更新2: 您可以在這裏看到最終的解決方案: https://gist.github.com/3501446
解決方案得到了它:https://gist.github.com/3501446 –