|
using System;
using System.Collections.Generic;
namespace Nelibur.Sword.DataStructures
{
internal sealed class SafeDictionary<TKey, TValue>
{
private readonly Dictionary<TKey, TValue> _dictionary = new Dictionary<TKey, TValue>();
private readonly object _locker = new object();
public TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory)
{
TValue result;
lock (_locker)
{
if (_dictionary.TryGetValue(key, out result))
{
return result;
}
}
TValue newValue = valueFactory(key);
lock (_locker)
{
if (_dictionary.TryGetValue(key, out result))
{
return result;
}
_dictionary[key] = newValue;
}
return newValue;
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
B.Sc. in Computer Science.