I recently had to use ReaderWriterLockSlim
to synchronize access to several resources that are shared between multiple threads. While doing it, I felt that using ReaderWriterLockSlim
is not easy specially when you have to use it in multiple places. You have to have try...finally
blocks and remember to open and close the locks. In many cases I've also found myself opening a write lock and closing a read lock instead of closing the write lock. Therefore I tried to come up with an easier way of using the ReaderWriterLockSlim
. This is where I got
class Locked<T>
{
private T _resource;
private ReaderWriterLockSlim _lock;
public Locked(T resource)
{
_resource = resource;
_lock = new ReaderWriterLockSlim();
}
public void Read(Action<T> ReadAction)
{
try
{
_lock.EnterReadLock();
ReadAction(_resource);
}
finally
{
_lock.ExitReadLock();
}
}
public void Write(Action<T> WriteAction)
{
try
{
_lock.EnterWriteLock();
WriteAction(_resource);
}
finally
{
_lock.ExitWriteLock();
}
}
}
Now for e.g. if we need to synchronize access to a List<string>
this is how we do it using the class above
public class Demo
{
private Locked<List<string>> _listOfString;
public Demo()
{
_listOfString = new Locked<List<string>>(new List<string>());
}
public void writeMethod(string value)
{
_listOfString.Write(list =>
{
list.Add(value);
});
}
public string readMethod(int index)
{
string value = null;
_listOfString.Read(list =>
{
value = list[index];
});
return value;
}
}
Do you think this approach is any better? Are there any shortcomings or flaws.