欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

共享锁using范围的实现方法

程序员文章站 2023-12-11 18:27:04
复制代码 代码如下:/// 共享锁 public class sharelock {   ...

复制代码 代码如下:

/// <summary>共享锁</summary>
public class sharelock
{
    readerwriterlock lock;
    idisposable readlock, writelock;

    public idisposable readlock { get { lock.acquirereaderlock(-1); return readlock; } }
    public idisposable writelock { get { lock.acquirewriterlock(-1); return writelock; } }
    public idisposable upgradelock { get { return new upgraderlocked(lock); } }
    /// <summary>释放所有锁</summary>
    public void releaselock() { lock.releaselock(); }

    public sharelock()
    {
        this.lock = new readerwriterlock();
        this.readlock = new locked(lock.releasereaderlock);
        this.writelock = new locked(lock.releasewriterlock);
    }
    class locked : idisposable
    {
        threadstart releaselock;
        public locked(threadstart releaselock) { this.releaselock = releaselock; }
        public void dispose() { this.releaselock(); }
    }
    class upgraderlocked : idisposable
    {
        delegate void releaselockhandler(ref lockcookie lockcookie);

        releaselockhandler releaselock;
        lockcookie cookie;
        public upgraderlocked(readerwriterlock locker)
        {
            cookie = locker.upgradetowriterlock(-1);
            this.releaselock = locker.downgradefromwriterlock;
        }
        public void dispose() { this.releaselock(ref cookie); }
    }
}

上一篇:

下一篇: