A wish: Execute under Lock method in sync objects

A wish: Execute under Lock method in sync objects

am 15.11.2007 13:49:49 von 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?

Re: A wish: Execute under Lock method in sync objects

am 15.11.2007 18:08:12 von Chris Mullins

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();
}
}

--
Chris Mullins

"valentin tihomirov" wrote in message
news:%23impYX4JIHA.5624@TK2MSFTNGP04.phx.gbl...
> 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?
>