Synchronization, ReaderWriterLockSlim, and Lambdas
Here is a synchronization wrapper that I wrote to wrap any object, and an implementation of a SynchronizedDictionary to show how to use it.
I offer this code as-is without any waranty to fitness, to the public domain, for any purpose you see fit.
Get a text version of this code here.
On with the show:
[UPDATE: get the code via the link, only ideas are shown below.]
Synchronized<T>:
wraps an instance of type T.
Contains 3 functions:
-
public TValue Read<TValue>(Func<T, TValue> readFunction)
- inside a reader lock, executes the readFunction.
-
public bool Write(Func<T, bool> writeFunction)
- inside a writer lock, executes the writeFunction, which should return the success nature of the write.
-
public IEnumerator<TValue> GetSynchronizedEnumerator<TValue>(Func<T, IEnumerator<TValue>> getEnumeratorFunction)
- returns an enumerator wrapped in a lock that releases when it is disposed.
An example of how to use the Synchronized<T> class:
namespace SynapticPop.DataStructures.Dictionaries {
public class SynchronizedDictionary<TKey, TValue> : IDictionary<TKey, TValue> {
private readonly Synchronized<IDictionary<TKey, TValue>> _synchronized;
public SynchronizedDictionary(IDictionary<TKey, TValue> dictionary) {
_synchronized = new Synchronized<IDictionary<TKey, TValue>>(dictionary);
}
...
public int Count {
get { return _synchronized.Read(dictionary => dictionary.Count); }
}
...
public void Add(TKey key, TValue value) {
_synchronized.Write(dictionary => { dictionary.Add(key, value); return true; });
}
...
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() {
return _synchronized.GetSynchronizedEnumerator(dictionary => dictionary.GetEnumerator());
}
...
}