当前位置: 编程技术>.net/c#/asp.net
共享锁using范围的实现方法
来源: 互联网 发布时间:2014-10-18
本文导语: 代码如下:/// 共享锁 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 writ...
代码如下:
/// 共享锁
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); } }
/// 释放所有锁
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); }
}
}