patterncsharpMinor
Extension methods for ReaderWriterLockSlim
Viewed 0 times
methodsreaderwriterlockslimforextension
Problem
In current project I'm using a lot
However I would like know, if you found some disadvantages in the extension methods I missed or forgot.
There are three extension methods:
There is code of
ReaderWriterLockSlim for synchronizing reading and writing values. Handling try { EnterReadLock(); .... } finaly { ExitReadLock(); } every time I need access value seems to me as copying code. So I created extension methods for ReaderWriterLockSlim which makes me coding much easer and faster (and reusable i think).However I would like know, if you found some disadvantages in the extension methods I missed or forgot.
There are three extension methods:
ReadOnly(this ReaderWriterLockSlim self, Func readFunc) // calls EnterReadLock()
Read(this ReaderWriterLockSlim self, Func readFunc) // calls EnterUpgradeableReadLock()
Write(this ReaderWriterLockSlim self, Action writeAction) // calls EnterWriteLock()
Write(this ReaderWriterLockSlim self, Func writeAction) // calls EnterWriteLock()
There is code of
ReadOnly(...) method. All methods looks similar.public static T ReadOnly(this ReaderWriterLockSlim self, Func readFunc) {
if (object.ReferenceEquals(self, null)) { throw new ArgumentNullException("self"); }
if (object.ReferenceEquals(readFunc, null)) { throw new ArgumentNullException("readFunc"); }
T result;
// flag, if lock was entered
bool lockEntered = false;
try {
// I don't want the ThreadAbortException during claiming the lock
Thread.BeginCriticalRegion();
try {
self.EnterReadLock();
lockEntered = true;
}
finally {
Thread.EndCriticalRegion();
}
result = readFunc();
}
finally {
// I don't want the ThreadAbortException during releasing the lock
Thread.BeginCriticalRegion();
try {
if (lockEntered) {
self.ExitReadLock();
}
}
finally {
Thread.EndCriticalRegion();
}
}
return result;
}Solution
It looks pretty good. I can't see anything less than great.
I'd just add that to your code:
And i used the
I'd just add that to your code:
private static void Critical(Action criticalAction)
{
try
{
Thread.BeginCriticalRegion();
criticalAction();
}
finally
{
Thread.EndCriticalRegion();
}
}And i used the
IsWriteLockHeld, IsReadLockHeld, etc, before exiting the lock.Code Snippets
private static void Critical(Action criticalAction)
{
try
{
Thread.BeginCriticalRegion();
criticalAction();
}
finally
{
Thread.EndCriticalRegion();
}
}Context
StackExchange Code Review Q#18908, answer score: 3
Revisions (0)
No revisions yet.