开发者

Is there an equivalent of the lock{} statement for ReaderWriterLockSlim?

开发者 https://www.devze.com 2023-01-29 07:18 出处:网络
I like the shortcut in C# of 开发者_JAVA技巧lock(myLock){ /* do stuff */}. Is there an equivalent for read/write locks? (Specifically ReaderWriterLockSlim.) Right now, I use the following custom metho

I like the shortcut in C# of 开发者_JAVA技巧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.

  1. Make DoWithWriteLock return an IDisposable
  2. Keep the TryEnterWriteLock call inside the DoWithWriteLock method
  3. Return an object that implements IDisposable. 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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消