I have made an attempt at creating a ThreadSafeSortedDictionary
, and I am working with .NET 4.0.
I have had a look at Thread safe SortedDictionary but not confident about the thread safety aspect.
Anyone think this can work, or NOT for a reason I cannot see associated with:
- Thread safety - it needs to be thread safe
- Performance/Efficiency - I am not majorly concerned about this (unless there is a huge problem with performance)
My code:
public class ThreadSafeSortedDict<TKey, TValue>
{
private readonly SortedDictionary<TKey, TValue> _dict;
private readonly ReaderWriterLockSlim _dictReaderWriterLockSlim;
private readonly ReaderWriterLockSlim _readonlyDictionaryLock;
public Dictionary<TKey, TValue> ReadOnly { get; set; }
public ThreadSafeSortedDict(IComparer<TKey> comparer)
{
_dict = new SortedDictionary<TKey, TValue>(comparer);
_dictReaderWriterLockSlim = new ReaderWriterLockSlim();
_readonlyDictionaryLock = new ReaderWriterLockSlim();
}
public void Add(TKey key, TValue value)
{
_dictReaderWriterLockSlim.EnterWriteLock();
try
{
_dict.Add(key,value);
}
finally
{
_dictReaderWriterLockSlim.ExitWriteLock();
}
SetReadOnlyDictionary();
}
public void AddRange(IEnumerable<KeyValuePair<TKey,TValue>> keyValues)
{
if (keyValues == null) return;
_dictReaderWriterLockSlim.EnterWriteLock();
try
{
foreach (var keyValue in keyValues)
{
Add(keyValue.Key, keyValue.Value);
}
}
finally
{
_dictReaderWriterLockSlim.ExitWriteLock();
}
SetReadOnlyDictionary();
}
public void Remove(TKey key)
{
_dictReaderWriterLockSlim.EnterWriteLock();
try
{
_dict.Remove(key);
}
finally
{
_dictReaderWriterLockSlim.ExitWriteLock();
}
SetReadOnlyDictionary();
}
public void Replace(IEnumerable<KeyValuePair<TKey, TValue>> newKeyValues)
{
if (newKeyValues == null) return;
_dictReaderWriterLockSlim.EnterWriteLock();
try
{
_dict.Clear();
AddRange(newKeyValues);
}
finally
{
_dictReaderWriterLockSlim.ExitWriteLock();
}
}
private void SetReadOnlyDictionary()
{
_readonlyDictionaryLock.EnterWriteLock();
try
{
ReadOnly = GetSortedKeyValues().ToDictionary(x => x.Key, x => x.Value);
}
finally
{
_readonlyDictionaryLock.ExitWriteLock();
}
}
private List<KeyValuePair<TKey, TValue>> GetSortedKeyValues()
{
_dictReaderWriterLockSlim.EnterReadLock();
try
{
return _dict.ToList();
}
finally
{
_dictReaderWriterLockSlim.ExitReadLock();
}
}
}