A wish: Execute under Lock method in sync objects

  • Thread starter Thread starter valentin tihomirov
  • Start date Start date
V

valentin tihomirov

It is quite convenient to use the basic primitive:

lock(object) {
method();
}

On the other hand,

rwLock.AcquireReaderLock(-1);
try { // unlock finally
method();
} finally {
rwLock.ReleaseReaderLock();
}

is much less cosy but is typical scenario, I beleive. I would prefer:

rwLock.RLock(-1) {
method();
}

instead. Why not to introduce the utility methods?
 
It is quite convenient to use the basic primitive:

lock(object) {
method();

}

On the other hand,

rwLock.AcquireReaderLock(-1);
try { // unlock finally
method();
} finally {
rwLock.ReleaseReaderLock();
}

is much less cosy but is typical scenario, I beleive. I would prefer:

rwLock.RLock(-1) {
method();
}

instead. Why not to introduce the utility methods?

You wouldn't really even need that - just make the AcquireReaderLock
method return a Disposable; then you can do:

using (rwLock.AcquireReaderLock())
{
method();
}

That's the approach I take with my own lock wrapper:
http://www.yoda.arachsys.com/csharp/miscutil/usage/locking.html

Jon
 
It's really pretty easy, and I do it all the time. Much like Jon's Padlock
class, I use something that looks like this:

public class ReadLock : IDisposable
{
private readonly ReaderWriterLock _rwlock;
public ReadLock(ReaderWriteLock rw)
{
_rwlock = rw;
_rwLock.AcquireReadLock(...);
}

public void Dispose()
{
_rwLock.ExitReadLock();
}
}
 
Back
Top