Consider the following extensions:
public static class ReaderWriteExt
{
public static void ExecWriteAction(this ReaderWriterLockSlim rwlock, Action action)
{
rwlock.EnterWriteLock();
try
{
action();
}
finally
{
rwlock.ExitWriteLock();
}
}
public static void ExecUpgradeableReadAction(this ReaderWriterLockSlim rwlock, Action action)
{
rwlock.EnterUpgradeableReadLock();
try
{
action();
}
finally
{
rwlock.ExitUpgradeableReadLock();
}
}
}
Also consider the following sample usage (stripped of some supporting code):
private static ReaderWriterLockSlim _rwlock = new ReaderWriterLockSlim();
private static ... _cacheEntries = ....;
public static void RemoveEntry(string name)
{
WeakReference outValue = null;
_rwlock.ExecUpgradeableReadAction(() =>
{
if (_cacheEntries.TryGetValue(name, out outValue))
{
if (!outValue.IsAlive)
{
_rwlock.ExecWriteAction(() => _cacheEntries.Remove(name));
}
}
});
}
I’m new to C# coding and I was unable to find enough information about these topics that could guide me. To my question: I am considering using this concept in our production code, is it a bad idea? What can go wrong?
That seems fine to me except that the code looks very cumbersome
I would probably implement
IDisposableas:Usage:
Similarly, you can implement
UpgradeableReadLockclass implementingIDisposableinterface.The idea is that you can create an instance of disposable class in
usingconstruct which ensures that in the constructor you enter into write lock by callingEnterWriteLock()method, and when it goes out of scope,Dispose()method is called automatically (by CLR) which callsExitWriteLock()method.Note that it will not dispose
ReaderWriterLockSlimobject; it will disposeWriteLockobject which is just a wrapper.ReaderWriterLockSlimwill be as such in the user-class.