I like the shortcut in C# of lock(myLock){ /* do stuff */}
. Is there an equivalent for read/write locks? (Specifically ReaderWriterLockSlim.) Right now, I use the following custom method, which I think works, but is kind of annoying because I have to pass in my action as an anonymous function, and I would prefer to use a standard locking mechanism if possible.
void bool DoWithWriteLock(ReaderWriterLockSlim RWLock, int TimeOut, Action Fn)
{
bool holdingLock = false;
try
{
if (RWLock.TryEnterWriteLock(TimeOut))
{
holdingLock = true;
Fn();
}
}
finally
{
if (holdingLock)
{
RWLock.ExitWriteLock();
}
}
return holdingLock;
}
You can't override the behaviour of the lock
keyword. A common technique is to hijack the using
keyword.
DoWithWriteLock
return an IDisposable
TryEnterWriteLock
call inside the DoWithWriteLock
methodIDisposable
. In that object's Dispose
method, put the call to ExitWriteLock
.The end result:
// Before
DoWithWriteLock(rwLock,
delegate
{
Do1();
Do2()
} );
// After
using (DoWithWriteLock(rwLock))
{
Do1();
Do2();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With