All,
It seems really natural to me to use the IDisposable pattern to control a ReaderWriterLockSlim lock, since it allows locks to be cleaned up without the extra cruft of a try/catch block. I notice that there is nothing in the BCL to take care of this common(ish) task, so I wonder if my code below is really naive? I see some other questions on SO related to this general area, but nothing that tackles the appropriateness of this idea head-on.
The question also is not about whether the Dispose() method on ReaderWriterLockSlim object should be called, just the wrapper.
public class LockWrapper : IDisposable
{
private readonly ReaderWriterLockSlim @lock;
private readonly bool writeRequired;
public LockWrapper(ReaderWriterLockSlim @lock, bool writeRequired)
{
this.@lock = @lock;
this.writeRequired = writeRequired;
if (writeRequired)
{
@lock.EnterWriteLock();
}
else
{
@lock.EnterReadLock();
}
}
public void Dispose()
{
if (writeRequired && @lock.IsWriteLockHeld)
{
@lock.ExitWriteLock();
}
else if (@lock.IsReadLockHeld)
{
@lock.ExitReadLock();
}
}
}
Usage:
var @lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
using(var lockWrapper = new LockWrapper(@lock, true))
{
//do something
}